*Linked List Cycle

mac2022-06-30  78

题目:

Given a linked list, determine if it has a cycle in it.

Follow up:Can you solve it without using extra space?

 

Analysis

If we have 2 pointers - fast and slow. It is guaranteed that the fast one will meet the slow one if there exists a circle.

The problem can be demonstrated in the following diagram:

 

1 public boolean hasCycle(ListNode head) { 2 ListNode fast = head; 3 ListNode slow = head; 4 5 while(fast!=null&&fast.next!=null&&fast.next.next!=null) 6 { 7 fast = fast.next.next; 8 slow = slow.next; 9 10 if(fast==slow)return true; 11 12 } 13 14 return false; 15 16 }

 

reference:http://www.programcreek.com/2012/12/leetcode-linked-list-cycle/

 

转载于:https://www.cnblogs.com/hygeia/p/4765430.html

最新回复(0)