141. Linked List Cycle

key idea: fast and slow pointers

核心: 快慢指针

Java example:

/**
 * 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 slow = head, fast = head.next;
        while(fast != null && fast.next != null){
            if(fast == slow) return true;
            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}

Python example:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        # edge case
        if head == None:
            return False
        
        # regular case
        slow = head
        fast = head.next
        while fast != None and fast.next != None:
            if fast == slow:  # fast.next == slow
                return True   # 想象fast 追 slow,总能追上的
            slow = slow.next
            fast = fast.next.next
            
        return False

Last updated