LeetCode链接:https://leetcode-cn.com/problems/linked-list-cycle-ii/submissions/
思路一:
同141题,快慢指针
1.链表判空
2.设置两个指针q和s,均从head开始
3.只要q不为空或者q下一跳不为空,q向后移两位,s向后移移位
4.移动过程中,如果q和s相遇,则退出3循环
5.此时q如果为空或者q的下一跳为空,说明无环,返回空节点
6.否则q接着后移,head也跟着后移,直到q和head相遇,此时q为出环结点
public class Solution {
public ListNode detectCycle(ListNode head) {
//1.
if (head == null || head.next == null)
return null;
//2.
ListNode q = head;
ListNode s = head;
//3.
while (q != null && q.next != null) {
q = q.next;
q = q.next;
s = s.next;
//4.
if (q == s)
break;
}
//5.
if (q == null || q.next == null)
return null;
//6.
while (q != head) {
q = q.next;
head = head.next;
}
return q;
}
}
思路二:
快慢指针问题,快指针向后一直走,慢指针每次从头走到快指针当前位置
如果慢指针在走的过程中遇见快指针,但是步数不同,则表示此处为出环点
1.链表判空
2.设置快慢指针slow和fast从head开始
3.定义count变量统计fast的移动次数
4.只要fast不为空,fast右移一位,且count++
5.fast移动后,slow每次从head开始,移动count次,如果移动过程中出现slow和fast相遇,但是步数不同,则此处出环点
6.如果4循环正常退出,则表示无环
public class Solution {
public ListNode detectCycle(ListNode head) {
//1.
if(head==null||head.next==null){
return null;
}
//2.
ListNode fast=head;
ListNode slow=head;
//3.
int count=0;
//4.
while(fast!=null){
fast=fast.next;
count++;
//5.
slow=head;
for(int i=1;i<=count;i++){
if(slow==fast&&i!=count){
return slow;
}
slow=slow.next;
}
}
//6.
return null;
}
}