题目
Linked List Cycle II
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?
标签
Linked List、Two Pointers
难度
中等
分析
题目意思是如果链表里面有回环,找出回环开始的位置,如果没有,返回null。我的做法是先判断链表是否有回环,判断回环的方法可以参照下文
http://blog.csdn.net/Timsley/article/details/51155365
如果找到回环,快指针指回表头,然后快慢指针继续走,快慢指针每次都是走一步,如果相遇,就找到这个指针,返回即可。
C代码实现
struct ListNode *detectCycle(struct ListNode *head)
{
struct ListNode *fast, *slow;
bool fgHasCycle = false;
if(!head)
return NULL;
fast = head;
slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
fgHasCycle = true;
break;
}
}
if(true == fgHasCycle)
{
fast = head;
while(fast)
{
if(fast == slow)
return fast;
fast = fast->next;
slow = slow->next;
}
}
else
return NULL;
}