Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
代码如下:
/**
* 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) {
if(!head)
return NULL;
ListNode* one = head;
ListNode* two = head;
bool isCycle = false;
while(two->next && two->next->next)
{
one = one->next;
two = two->next->next;
if(one == two)
{
isCycle = true;
break;
}
}
if(isCycle == false)
return NULL;
one = head;
while(one != two)
{
one = one->next;
two = two->next;
}
return one;
}
};
本文介绍了一种在不使用额外空间的情况下找到链表中循环起始节点的方法。通过使用快慢指针技巧来判断链表是否存在循环,并最终定位到循环开始的位置。
1210

被折叠的 条评论
为什么被折叠?



