Double Pointers

Break loop

See also 141, 142

clip

void dectectAndRemoveLoop(Node node){
    // if list is empty or has only one node
    if (node == null){
        return;
    }

    Node slow = node, fast = node;

    // search for loop
    while (fast != null && fast.next != null){
        slow = slow.next;
        fast = fast.next.next;
        if (fast == slow){
            // search connected node and remove the loop
            slow = node;
            while(slow.next != fast.next){
                slow = slow.next;
                fast = fast.next;
            }
            fast.next = null;
            break;
        }
    }
}

287. Find the Duplicate Number

LinkedList Cycle index: 0, 1, 2, 3, 4, 5, 6 value: 2, 6, 4, 1, 3, 1, 5 It value can be index, it will become a cycled linkedlist 0 - > 2 - > 4 -> 3 -> 1 -> 6 -> 5-> [1- >6-> 5 ->1 链表环]

61 Rotate List

Given a linked list, rotate the list to the right by k places, where k is non-negative.

1 create dummy node, a slow and a fast pointer == dummy node 2 get length, fast node move to last 3 slow node move to break index 4 rotate lsit

138 Copy List with random pointer

  • HashMap[oldNode, newNode]

  • first loop create newNode

  • Second loop update next and random pointers

  • Space O(n)

Space O(1) 1 -> 1' -> 2 -> 2' -> 3 -> 3' -> null

1. Copy new nodes after old nodes (including label, next and random)

2. Update random pointers

3. Split the linkedList

Last updated

Was this helpful?