题目描述
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
进阶:
你是否可以使用 O(1) 空间解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//思路:先判断是否有环,再判断换的入口在哪
//使用快慢指针判段是否有环,如果有环,因为快指针走的快,肯定会和慢指针相遇
ListNode * fast=head;
ListNode * slow=head;
ListNode * p=head;
while( fast!=NULL && fast->next!=NULL && fast->next->next!=NULL ){ //等于null就说明没有环了
fast=fast->next->next;
slow=slow->next;
if(fast==slow){ //快慢指针第一次相遇了,说明有环,开始找环入口。
while(fast!=p){ //接下来fast和slow用哪一个都可以
fast=fast->next;
p=p->next;
}
return p;
}
}
return NULL;
}
};
注意
while( fast!=NULL && fast->next!=NULL && fast->next->next!=NULL )
该句,我之前使用的是
while( slow->next!=NULL && fast->next->next!=NULL )
提交后就开始报错:Line 18: Char 22: runtime error: member access within null pointer of type 'ListNode' (solution.cpp)
原因在于对于哪些没有环的链表,还没有判断fast就开始判断fast->next->next了,就会牵扯到空指针。所以这个顺序不能乱也不能少。至于slow,因为fast走的快,slow不用再判断了。
JAVA
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode meetNode1=isLoop(head);
if(meetNode1==null)
return null; //无环
//有环,找环中的节点个数n
int n=1;
ListNode cur=meetNode1.next;
while(cur!=meetNode1){
n++;
cur=cur.next;
}
ListNode A=head;
ListNode B=head;
//A先移动n个节点
for(int i=1;i<=n;i++){
A=A.next;
}
//AB一起移动,直到相遇
while(A!=B){
A=A.next;
B=B.next;
}
return A;
}
public ListNode isLoop(ListNode head){
if(head==null)
return null;
ListNode B=head.next;
if(B==null) return null;
ListNode A=B.next;
while(A!=null && B!=null){
if(A==B)
return A;
B=B.next;
A=A.next;
if(A!=null){
A=A.next;
}
}
return null;
}
}