Linked List Cycle

当一个步长为奇数,另一个步长为偶数时,依次从头找起,如果有环最终两指针会相遇的!

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12        if(head==NULL) return false; 
13        ListNode *p=head;
14         while(p->next&&p->next->next)
15         {
16             head=head->next;
17             p=p->next->next;
18             if(p==head)
19              return true;
20         }
21         return false;
22     }
23 };

 

posted on 2015-10-19 21:15  RenewDo  阅读(99)  评论(0编辑  收藏  举报

导航