Monday, August 08, 2016

split linked list into halves

Split such that count(first) >= count(second)
    s
1-2-3-4-5
        f

  s
1-2-3-4 
    f

s
1-2
f

s
1
f

s
-
f
(n):
    if n == null:
        return {null, null}
    first = n
    slow = fast = n
    while fast != null 
        && fast.next != null 
        && fast.next.next != null:
        slow = slow.next
        fast = fast.next.next
    second = slow.next
    slow.next = null
    return {first, second}

No comments:

Post a Comment