环形链表 II

Bernie


Bernie
203. 环形链表 II
思路:
-
先判断 head 以及 head.Next 是否有值,无则直接返回 null
-
用 fast, slow 分别指向 head, fast 每次走两步,slow 每次走一步,当 fast === slow 时,跳出循环
-
重新将 fast 指向 head, 然后 fast, slow 每次走一步,当 fast === slow 时,跳出循环
-
返回 fast 或者 slow
typescript 解法
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function detectCycle(head: ListNode | null): ListNode | null {
if (!head || !head.next) {
return null;
}
let fast = head;
let slow = head;
while (fast && fast.next) {
fast = fast.next.next;
slow = slow.next;
if (fast === slow) {
break;
}
}
fast = head;
while (slow && slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
go 解法
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return nil
}
fast, slow := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
break
}
}
fast = head
for slow != nil && fast != nil && fast != slow {
slow = slow.Next
fast = fast.Next
}
return slow
}