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.
题意:
给定一个链表,如果存在环,返回环开始的链表节点,如果不存在环返回空。注意:不要修改链表。
思路:
首先判断是否存在环,思路同141. Linked List Cycle,对单恋表快慢指针相遇后,相遇点到环起始点,以及单链表头到环起始点的距离进行总结,可以得到如下结论——相遇点到环起始点的距离和链表头到环起始点的距离相同(不带链表头结点);相遇点到环起始点的距离和链表头到环起始点的距离相差1(带链表头结点,因为ListNode head(-1);会增加1个距离)。
1 | 切记此结论是从相遇点起算起到环起始点的距离,以及快指针是慢指针的2倍移动速度。 |
1 | ListNode* detectCycle(ListNode *head) { |