标签:head ListNode List 44 list II 指针 linked cycle
Level:
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; //未能相遇则不存在环
}
}
标签:head,ListNode,List,44,list,II,指针,linked,cycle 来源: https://www.cnblogs.com/yjxyy/p/11080371.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。