标签:
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.另p1=node first met,p2=node from the start. 然后just walk one step each time, 当p1与p2相遇时,即找到圆的起点。
这个思路有木有很diao!!(申明不是我想的)哈哈哈,leetcode下面的神评论把我笑死了!
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *p1,*p2; p1=p2=head; bool isCycled=false; while(p1 && p2 && p2->next){ p1=p1->next; p2=p2->next->next; if(p1==p2) {isCycled=true;break;} } p2=head; while(isCycled){ if(p2==p1) return p1; p2=p2->next; p1=p1->next; } return NULL; } };
标签:
原文地址:http://www.cnblogs.com/renrenbinbin/p/4341366.html