[leetcode] 141 ring list

Time:2020-1-21

Circular linked list

subject

Given a link list, determine whether there are links in the link list.

In order to represent the links in a given linked list, we use the integer POS to represent the position where the end of the linked list is connected to the linked list (the index starts from 0). If POS is – 1, there are no rings in the list.

Example 1:
Input: head = [3,2,0, – 4], POS = 1
Output: true
Explanation: there is a link in the list with the tail connected to the second node.

Example 2:
Input: head = [1,2], POS = 0
Output: true
Explanation: there is a link in the list with the tail connected to the first node.

Example 3:
Input: head = [1], POS = – 1
Output: false
Explanation: there are no links in the list.

Advance:
Can you use o (1) (that is, constant) memory to solve this problem?

Solving problems

This problem can be solved with speed pointer.

Two steps for fast pointer and one step for slow pointer. If the fast pointer catches up with the slow pointer, it means that there is a link in the list (like two people running on the playground, one running fast, one running slowly, and the fast one will catch up with the slow one eventually).

Code

class Solution {
    
    /**
     *Use the fast and slow pointer. The fast pointer moves 2 steps at a time and the slow pointer moves 1 step at a time. If the fast pointer catches up with the slow pointer, it indicates that there is a ring
     */
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == 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;
    }
}