Skip to content

Instantly share code, notes, and snippets.

@whwkong
Last active February 19, 2021 14:45
Show Gist options
  • Select an option

  • Save whwkong/066f8f74bbd2f44817911bae4ce8e49f to your computer and use it in GitHub Desktop.

Select an option

Save whwkong/066f8f74bbd2f44817911bae4ce8e49f to your computer and use it in GitHub Desktop.
Merge Linked Lists in Python
@nycmitch25
Copy link
Copy Markdown

This code actually doesn't work correctly all of the time. because of .next being missing in some cases I believe causing runtime error. Also probably want a <= compare . I'm only guessing. However this code works:

`def mergeListsOLD(headA, headB):

# A dummy node to store the result
dummyNode = SinglyLinkedListNode(0)

# Tail stores the last node
tail = dummyNode
while True:

    # If any of the list gets completely empty
    # directly join all the elements of the other list
    if headA is None:
        tail.next = headB
        break
    if headB is None:
        tail.next = headA
        break

    # Compare the data of the lists and whichever is smaller is
    # appended to the last of the merged list and the head is changed
    if headA.data <= headB.data:
        tail.next = headA
        headA = headA.next
    else:
        tail.next = headB
        headB = headB.next

    # Advance the tail
    tail = tail.next

# Returns the head of the merged list
return dummyNode.next

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment