*Linked List Cycle

题目

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:
linked-list-cycle

 

 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/

 

posted @ 2015-08-28 08:44  Hygeia  阅读(129)  评论(0编辑  收藏  举报