Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
这个求单链表中的环的起始点是之前那个判断单链表中是否有环的延伸,可参见我之前的一篇文章 (http://www.cnblogs.com/grandyang/p/4137187.html). 还是要设快慢指针,不过这次要记录两个指针相遇的位置,当两个指针相遇了后,让其一指针从链表头开始,一步两步,一步一步似爪牙,似魔鬼的步伐。。。哈哈,打住打住。。。此时再相遇的位置就是链表中环的起始位置。代码如下:
/** * 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 || !head->next) return NULL; ListNode *slow = head; ListNode *fast = head; while (true) { slow = slow->next; fast = fast->next; if (!fast || !fast->next) return NULL; fast = fast->next; if (fast == slow) break; } slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return fast; } };
单链表中的环的问题还有许多扩展,比如求环的长度,或者是如何解除环等等,可参见网上大神的总结 (http://www.cnblogs.com/hiddenfox/p/3408931.html).
时间: 2024-10-10 01:46:33