题目描述
相对于环形链表 ,这里要求找到环的起点 难点在于 O(1),否则可以直接哈希表冲
思路 & 代码
public class Solution {
public ListNode detectCycle ( ListNode head) {
ListNode slow = head, fast = head;
while ( true ) {
if ( fast == null || fast. next == null ) {
return null ;
}
slow = slow. next;
fast = fast. next. next;
if ( fast == slow) {
break ;
}
}
fast = head;
while ( fast != slow) {
fast = fast. next;
slow = slow. next;
}
return fast;
}
}
更新版
虽然但是,感觉有稍微优化了一下 while 结构= =
public class Solution {
public ListNode detectCycle ( ListNode head) {
ListNode slow = head, fast = head;
do {
if ( fast == null || fast. next == null ) {
return null ;
}
slow = slow. next;
fast = fast. next. next;
} while ( slow != fast) ;
fast = head;
while ( fast != slow) {
fast = fast. next;
slow = slow. next;
}
return fast;
}
}
三刷 - 再更新
选取了一个我更喜欢的结构! 成环情况,直接开找,然后return
public class Solution {
public ListNode detectCycle ( ListNode head) {
ListNode fast = head, slow = head;
while ( fast != null && fast. next != null ) {
fast = fast. next. next;
slow = slow. next;
if ( fast == slow) {
fast = head;
while ( fast != slow) {
fast = fast. next;
slow = slow. next;
}
return fast;
}
}
return null ;
}
}