I could not find a simple implementation Merge Sortin Python for Linked Listsanywhere. Here is what I tried:
Definition for a singly linked list:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
Implementation of merge sort:
def mergeSortLinkedList(A):
if A == None or A.next == None:
return A
leftHalf, rightHalf = splitTheList(A)
mergeSortLinkedList(leftHalf)
mergeSortLinkedList(rightHalf)
return mergeTheLists(leftHalf, rightHalf)
Split:
def splitTheList(sourceList):
if sourceList == None or sourceList.next == None:
leftHalf = sourceList
rightHalf = None
return leftHalf, rightHalf
else:
midPointer = sourceList
frontRunner = sourceList.next
while frontRunner != None:
frontRunner = frontRunner.next
if frontRunner != None:
frontRunner = frontRunner.next
midPointer = midPointer.next
leftHalf = sourceList
rightHalf = midPointer.next
midPointer.next = None
return leftHalf, rightHalf
Merge:
def mergeTheLists(leftHalf, rightHalf):
fake_head = ListNode(None)
curr = fake_head
while leftHalf and rightHalf:
if leftHalf.val < rightHalf.val:
curr.next = leftHalf
leftHalf = leftHalf.next
else:
curr.next = rightHalf
rightHalf = rightHalf.next
curr = curr.next
if leftHalf == None:
curr.next = rightHalf
elif rightHalf == None:
curr.next = leftHalf
return fake_head.next
Data:
nodeA1 = ListNode(2)
nodeA2 = ListNode(1)
nodeA1.next = nodeA2
nodeA3 = ListNode(9)
nodeA2.next = nodeA3
nodeA4 = ListNode(3)
nodeA3.next = nodeA4
nodeC1 = ListNode(5)
nodeA4.next = nodeC1
nodeC2 = ListNode(6)
nodeC1.next = nodeC2
nodeC3 = ListNode(4)
nodeC2.next = nodeC3
nodeC4 = ListNode(5)
nodeC3.next = nodeC4
Expected Result on Call mergeSortLinkedList(nodeA1):
1 2 3 4 5 5 6 9
Instead, I get the following:
2 5 6 9
I can’t understand where the slip is. Please, help.
source
share