44.Linked List Cycle II(环的入口节点)
Posted yjxyy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了44.Linked List Cycle II(环的入口节点)相关的知识,希望对你有一定的参考价值。
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; //未能相遇则不存在环
以上是关于44.Linked List Cycle II(环的入口节点)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode链表--6linked-list-cycle-ii(有环单链表环的入口结点)