标签:int img 代码 begin follow not integer 思路分析 相等
??Medium
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?
??如果存在环,设置一个快指针,一个慢指针,那么快指针一定会追上慢指针相遇,此时相遇的节点一定在环内,这时可以求出环内节点的数目,然后设置一个前指针和后指针初始值都为head,让前指针先走n次,然后前后指针一起走,如果相等时,则该节点就为环入口节点
public class Solution{
public ListNode detectCycle(ListNode head){
ListNode meetNode=meetNoding(head);
if(meetNode==null)
return null;
ListNode pNode=meetNode;
int count=1;
while(pNode.next!=meetNode){
count++;
pNode=pNode.next;
}
ListNode slow=head;
ListNode fast=head;
for(int i=0;i<count;i++){
slow=slow.next;
}
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;
}
//求相遇的节点
public ListNode meetNoding(ListNode head){
if(head==null)
return null;
if(head.next==null)
return null;
ListNode slow=head.next;
ListNode fast=slow.next;
while(slow!=null&&fast!=null){
if(slow==fast)
return fast;
slow=slow.next;
fast=fast.next;
if(fast!=null&&fast.next!=null)
fast=fast.next; //快指针一次走两步
}
return null; //未能相遇则不存在环
}
}
44.Linked List Cycle II(环的入口节点)
标签:int img 代码 begin follow not integer 思路分析 相等
原文地址:https://www.cnblogs.com/yjxyy/p/11080371.html