环形链表
01 思路
快慢指针
- fast指针每次向后走两步,slow 指针每次向后走一步
- 如果说链表中没有环,fast指针一定先走到bull
02 代码
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode s = head;
ListNode f = head;
while(f != null && f.next != null) {
s = s.next;
f = f.next.next;
if(f == s) return true;
}
return false;
}
}
环形链表II
01 思路
02 代码
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode f = head;
ListNode s = head;
while(f != null && f.next != null) {
s = s.next;
f = f.next.next;
if(s == f) {
s = head;
while(s != f) {
s = s.next;
f = f.next;
}
return s;
}
}
return null;
}
}