题目网址:https://leetcode-cn.com/problems/linked-list-cycle/
基本思路,我们采用快慢指针的方法,快指针一次走两步,慢指针一次走一步。
如果链表不带环,快指针一定会先到达末尾
如果链表带环,快指针一定会和慢指针重合。
时间复杂度? O(N)
空间复杂度?O(1)

具体实现代码:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
}
如果快指针一次走三步,满指针一次走一步,行不行?
反例,这与速度差有关,速度差如果为1,就能相遇

返回该带环链表的入口节点
先上结论,记节点meet为快慢指针相遇的节点,头节点~环入口节点 的长度 = meet ~环入口节点
头节点到入口环节点的长度 等于 快慢指针相遇节点到环入口节点的长度
x = y

证明,设环的长度为cycle
慢指针走过的距离: x + cycle - y
快指针走过的距离: x + 2cycle - y
由于快指针的速度是慢指针的两倍,所以路程也是慢指针的两倍
x + 2cycle - y = 2(x + cycle - y)
x + 2cycle - y = 2x + 2cycle -2y
得出
x = y
实际上 快指针:x + Ncycle - y
但也不影响
x-y = Ncycle
两个节点(从头出发,从meet出发)总会相遇,就是看走几圈的问题了
题目网址:https://leetcode-cn.com/problems/linked-list-cycle-ii/
具体实现代码
/**
* 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) {
if(head == null){
return null;
}
//从链表头部出发,到入口点距离
//从快慢指针相遇处出发,到入口点距离
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
break;
}
}
if(fast == null || fast.next == null){
//空链表的情况
return null;
}
ListNode cur1 = head;
ListNode cur2 = fast;
while(cur1 != cur2){
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur1;
}
}

使用快慢指针法解决链表环判断问题,当快指针与慢指针相遇时找到链表环的入口节点。分析了时间复杂度O(N)和空间复杂度O(1),并探讨了不同速度差对结果的影响。给出具体实现代码。

5万+





