求单链表环的入口结点 Linked List Cycle II
2013-11-22 21:21
309 查看
对于单链表,有的没有环,最后一个结点指向NULL,从头遍历到NULL就结束了。而有的是存在环,那么遍历时会在环内死循环,没有结尾。
本题目源自于leetcode。经典题目。
题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.solve it without using extra space.
思路:
slow指针每次走1步,fast指针每次走2步。如果链表有环,那么两个指针一定会相遇。
设链表头到环入口结点的结点数目是a,环内的结点数目r。假设相遇时,fast指针已经绕环转了n圈,比slow多走了n*r步。假设环的入口结点到相遇结点的结点数目为x。
那么在相遇时,slow走了a+x步,fast走了a+x+n*r步。
由于fast的步调是slow的两倍,所以有a+x = n*r。因而,a = n*r - x
显然,从相遇位置开始,走n*r - x步,一定可以到达环的入口结点;从链表头开始,走a步,也会到达环的入口。并且我们得到了a = n*r - x。所以我们让两个指针,一个从相遇位置出发一个从链表头出发,让他们都单步前进。因为a = n*r - x,所以他们一定会在环的入口相遇。
具体做法:
第一次遍历用slow指针和fast指针遍历,相遇时,记下相遇位置。
第二次遍历p1指针从链表头出发,p2指针从上次的相遇位置出发,p1p2相遇时所在的位置就是环的入口。
代码:
本题目源自于leetcode。经典题目。
题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.solve it without using extra space.
思路:
slow指针每次走1步,fast指针每次走2步。如果链表有环,那么两个指针一定会相遇。
设链表头到环入口结点的结点数目是a,环内的结点数目r。假设相遇时,fast指针已经绕环转了n圈,比slow多走了n*r步。假设环的入口结点到相遇结点的结点数目为x。
那么在相遇时,slow走了a+x步,fast走了a+x+n*r步。
由于fast的步调是slow的两倍,所以有a+x = n*r。因而,a = n*r - x
显然,从相遇位置开始,走n*r - x步,一定可以到达环的入口结点;从链表头开始,走a步,也会到达环的入口。并且我们得到了a = n*r - x。所以我们让两个指针,一个从相遇位置出发一个从链表头出发,让他们都单步前进。因为a = n*r - x,所以他们一定会在环的入口相遇。
具体做法:
第一次遍历用slow指针和fast指针遍历,相遇时,记下相遇位置。
第二次遍历p1指针从链表头出发,p2指针从上次的相遇位置出发,p1p2相遇时所在的位置就是环的入口。
代码:
/** * 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 == NULL) return NULL; ListNode *fast, *slow; fast = slow = head; while(fast->next != NULL && fast->next->next!= NULL) { slow = slow->next; fast = fast->next->next; if(fast == slow) //slow和fast相遇 break; } if(fast->next == NULL || fast->next->next == NULL) return NULL; slow = head; //slow从链表头开始,fast从刚才的相遇位置开始。它们会在环的入口相遇。 while(slow != fast) { slow = slow->next; fast = fast->next; } return slow; } };
相关文章推荐
- Linked List Cycle II 求单链表环的入口
- 142 Linked List Cycle II(如果链表有环,找到入口结点Medium)
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- Leetcode Linked List Cycle II 循环链表入口
- 2.2.12—单链表—Linked List Cycle II
- LeetCode Linked List Cycle II 单链表环2 (找循环起点)
- 数据结构与算法[LeetCode]—Linked List Cycle 确定单链表是否有环,并找出第一个环结点
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- Linked List Cycle leetcode II java (寻找链表环的入口)
- Linked List Cycle II 找链表环入口 @LeetCode
- Linked List Cycle leetcode II java (寻找链表环的入口)
- Linked List Cycle II
- 算法系列——Linked List Cycle II
- leetcode之Linked List Cycle以及Linked List Cycle II
- Linked List Cycle II
- 重拾编程之路--Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II Linked List Cycle
- Leetcode Linked List Cycle II
- [C++]LeetCode: 74 Linked List Cycle II