leetcode - Linked List Cycle II

leetcode - Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

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

 

 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     ListNode *detectCycle(ListNode *head) {
12         if(NULL == head || NULL == head->next) return NULL;
13         ListNode *p1 = head->next;
14         ListNode *p2 = head->next->next;
15         while(p2 != NULL && p2->next != NULL && p1 != p2){
16             p1 = p1->next;
17             p2 = p2->next->next;
18         }
19         if(p1 == p2){
20             ListNode *tp = head;
21             while(tp != p2){
22                 tp=tp->next;
23                 p2=p2->next;
24             }
25             return tp;
26         }
27         else return NULL;
28     }
29 };

 

两个指针ptr1和ptr2,都从链表头开始走,ptr1每次走一步,ptr2每次走两步,等两个指针重合时,就说明有环,否则没有。如果有环的话,那么让ptr1指向链表头,ptr2不动,两个指针每次都走一步,当它们重合时,所指向的节点就是环开始的节点。

http://blog.sina.com.cn/s/blog_6f611c300101fs1l.html#cmt_3246993

posted @ 2015-07-14 17:53  cnblogshnj  阅读(137)  评论(0编辑  收藏  举报