Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
题意:找到循环链表的初始位置。
思路:
1.还是先用快慢指针方法,找出快慢指针相遇的点;
2.重新定义两个指针,一个为head,另一个为相遇的节点;
3.然后两个指针每次走一步,相遇点则是链表环的起点;
class Solution
{
public:
ListNode* detectCycle(ListNode* head)
{
if (head==NULL)
{
return NULL;
}
ListNode* slow = head;
ListNode* fast = head;
while (fast!=NULL && fast->next!=NULL)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
ListNode* node1 = head;
ListNode* node2 = fast;
while (node1!=node2)
{
node1 = node1->next;
node2 = node2->next;
}
return node1;
}
}
return NULL;
}
};