Last active
February 19, 2021 14:45
-
-
Save whwkong/066f8f74bbd2f44817911bae4ce8e49f to your computer and use it in GitHub Desktop.
Merge Linked Lists in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| For complete problem definition, see: https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists | |
| Merge two linked lists | |
| head could be None as well for empty list | |
| Node is defined as | |
| class Node(object): | |
| def __init__(self, data=None, next_node=None): | |
| self.data = data | |
| self.next = next_node | |
| return back the head of the linked list in the below method. | |
| """ | |
| def MergeLists(headA, headB): | |
| if headA is None and headB is None: | |
| return None | |
| if headA is None: | |
| return headB | |
| elif headB is None: | |
| return headA | |
| ret = Node() | |
| if headA.data < headB.data: | |
| ret = headA | |
| ret.next = MergeLists(headA.next, headB) | |
| else: | |
| ret = headB | |
| ret.next = MergeLists(headA, headB.next) | |
| return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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):
`