leetcode [142]Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it without using extra space?
题目大意:
如果链表中存在环,返回环的入口,否则返回空。
解法:
1.先使用快慢指针,快指针走两步,慢指针走一步,判断链表中是否存在环,如果快慢指针相遇,则不存在,否则快指针先走到链表最后,返回null。
2.然后再让快慢指针相遇一次,计算得到环的长度
3.重新让快慢指针都指向头结点,快指针先走环的长度的步数,当快慢指针再相遇的时候,该节点就是环的入口。
java:
public class Solution { public ListNode detectCycle(ListNode head) { ListNode slow=head,fast=head; if(head==null) return null; while(fast!=null&&fast.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast) break; } if(fast==null || fast.next==null) return null; int count=0; while(count==0||slow!=fast){ slow=slow.next; fast=fast.next.next; count++; } slow=head; fast=head; while(count!=0){ fast=fast.next; count--; } while(slow!=fast){ slow=slow.next; fast=fast.next; } return slow; } }