Tuesday, January 21, 2014

fix cyclic linked list

Last node always forms the cycle in linked list. Get the meet node first (where slow and fast pointers meet), then the last node, and null its next.

node getCyclicLinkedListMeetNode(root):
    slow = root
    fast = root
    while fast != null && fast.next != null:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            break
    meet = null
    if slow == fast:
        meet = fast
    return meet

void fixCyclicLinkedList(root):
    meet = getCyclicLinkedListMeetNode(root)
    // not cyclic
    if meet == null:
        return
    // if last node connects to root, then meet is root
    if meet == root:
        // go to last node
        last = root
        while last.next != root:
            last = last.next
    // else go to the last node from meet
    else:
        last = meet
        n = root
        while n.next != last.next:
            n = n.next
            last = last.next
    // fix
    last.next = null

cases:

// last connects to other than root

            meet
    1-->2-->3
        |   |
        -----

           meet
    1-->2-->3-->4
            |   |
            -----

// last connects to root

 meet
    1-->2-->3
    |       |
    ---------

 meet
    1-->2
    |   |
    -----

 meet
    1--
    | |
    ---

No comments:

Post a Comment