|
| 1 | +# Python3 program to merge sort of linked list |
| 2 | + |
| 3 | +class Node: |
| 4 | + def __init__(self, data): |
| 5 | + self.data = data |
| 6 | + self.next = None |
| 7 | + |
| 8 | +class LinkedList: |
| 9 | + def __init__(self): |
| 10 | + self.head = None |
| 11 | + |
| 12 | + # push new value to linked list |
| 13 | + def append(self, new_value): |
| 14 | + new_node = Node(new_value) |
| 15 | + if self.head is None: |
| 16 | + self.head = new_node |
| 17 | + return |
| 18 | + curr_node = self.head |
| 19 | + while curr_node.next is not None: |
| 20 | + curr_node = curr_node.next |
| 21 | + |
| 22 | + # Append the new node at the end |
| 23 | + curr_node.next = new_node |
| 24 | + |
| 25 | + def sortedMerge(self, a, b): |
| 26 | + result = None |
| 27 | + |
| 28 | + # Base cases |
| 29 | + if a == None: |
| 30 | + return b |
| 31 | + if b == None: |
| 32 | + return a |
| 33 | + |
| 34 | + if a.data <= b.data: |
| 35 | + result = a |
| 36 | + result.next = self.sortedMerge(a.next, b) |
| 37 | + else: |
| 38 | + result = b |
| 39 | + result.next = self.sortedMerge(a, b.next) |
| 40 | + return result |
| 41 | + |
| 42 | + def mergeSort(self, h): |
| 43 | + |
| 44 | + # Base case if head is None |
| 45 | + if h == None or h.next == None: |
| 46 | + return h |
| 47 | + |
| 48 | + # get the middle of the list |
| 49 | + middle = self.getMiddle(h) |
| 50 | + nexttomiddle = middle.next |
| 51 | + |
| 52 | + middle.next = None |
| 53 | + |
| 54 | + # Apply mergeSort on left list |
| 55 | + left = self.mergeSort(h) |
| 56 | + |
| 57 | + # Apply mergeSort on right list |
| 58 | + right = self.mergeSort(nexttomiddle) |
| 59 | + |
| 60 | + # Merge the left and right lists |
| 61 | + sortedlist = self.sortedMerge(left, right) |
| 62 | + return sortedlist |
| 63 | + |
| 64 | + def getMiddle(self, head): |
| 65 | + if (head == None): |
| 66 | + return head |
| 67 | + |
| 68 | + slow = head |
| 69 | + fast = head |
| 70 | + |
| 71 | + while (fast.next != None and |
| 72 | + fast.next.next != None): |
| 73 | + slow = slow.next |
| 74 | + fast = fast.next.next |
| 75 | + |
| 76 | + return slow |
| 77 | + |
| 78 | +def printList(head): |
| 79 | + if head is None: |
| 80 | + print(' ') |
| 81 | + return |
| 82 | + curr_node = head |
| 83 | + while curr_node: |
| 84 | + print(curr_node.data, end = " ") |
| 85 | + curr_node = curr_node.next |
| 86 | + print(' ') |
| 87 | + |
| 88 | +if __name__ == '__main__': |
| 89 | + li = LinkedList() |
| 90 | + |
| 91 | + li.append(15) |
| 92 | + li.append(10) |
| 93 | + li.append(5) |
| 94 | + li.append(20) |
| 95 | + li.append(3) |
| 96 | + li.append(2) |
| 97 | + |
| 98 | + # Apply merge Sort |
| 99 | + li.head = li.mergeSort(li.head) |
| 100 | + print ("Sorted Linked List is:") |
| 101 | + printList(li.head) |
0 commit comments