142、Linked List Cycle II

problem:

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?

Hide Tags

Linked ListTwo Pointers

题意:如果一个单链表存在环形结构,返回环的起点。空间复杂度满足O(1)

thinking:

(1)上一题使用快慢指针可以判断是否存在环形结构,当fast==slow时,他俩指向的结点是环形结点的任意一个,与环的大小和位置有关。

(2)改造如下:慢指针和快指针都从头节点开始,慢指针每次走一步,,快指针每次走两步,当slow==fast时,fast不变,slow回到起点head处,

此时快慢指针每次都走一步,再次相等时,两指针指向的节点即为环形的起点,也为终点。

举例证明: 1->2->3->2, 3指向前一个节点2

当快慢指针第一次相遇时,同时指向3,将慢指针重置到1,每次前进一步,再次相遇时,两个指针同时指向2,即为环形起点

(3)细节:快慢指针都从head开始,起点要一致。

code:

class Solution {public:ListNode *detectCycle(ListNode *head) {if(head==NULL)return head;ListNode *slow=head;ListNode *fast=head;while(fast->next!=NULL && fast->next->next!=NULL){slow=slow->next;fast=fast->next->next;if(slow==fast){slow=head;while(slow!=fast){slow=slow->next;fast=fast->next;}return slow;}}return NULL;}};

在时间里面我们什么也不能留下,包括痛苦,快乐和生命。

142、Linked List Cycle II

相关文章:

你感兴趣的文章:

标签云: