|
| 1 | +""" |
| 2 | +Given a linked list with head pointer, |
| 3 | +sort the linked list using quicksort technique without using any extra space |
| 4 | +Time complexity: O(NlogN), Space complexity: O(1) |
| 5 | +""" |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | + |
| 9 | +class Node: |
| 10 | + def __init__(self, data: int) -> None: |
| 11 | + self.data = data |
| 12 | + self.next = None |
| 13 | + |
| 14 | + |
| 15 | +class LinkedList: |
| 16 | + def __init__(self): |
| 17 | + self.head = None |
| 18 | + |
| 19 | + # method to insert nodes at the start of linkedlist |
| 20 | + def insert(self, new_data: int) -> None: |
| 21 | + new_node = Node(new_data) |
| 22 | + new_node.next = self.head |
| 23 | + self.head = new_node |
| 24 | + |
| 25 | + # method to print the linkedlist |
| 26 | + def printLL(self) -> None: |
| 27 | + temp = self.head |
| 28 | + if temp == None: |
| 29 | + return 'Linked List is empty' |
| 30 | + while temp.next: |
| 31 | + print(temp.data, '->', end='') |
| 32 | + temp = temp.next |
| 33 | + print(temp.data) |
| 34 | + return |
| 35 | + |
| 36 | +# Partition algorithm with pivot as first element |
| 37 | + |
| 38 | + |
| 39 | +def partition(start, end): |
| 40 | + if start == None or start.next == None: |
| 41 | + return start |
| 42 | + prev, curr = start, start.next |
| 43 | + pivot = prev.data |
| 44 | + while curr != end: |
| 45 | + if curr.data < pivot: |
| 46 | + prev = prev.next |
| 47 | + temp = prev.data |
| 48 | + prev.data = curr.data |
| 49 | + curr.data = temp |
| 50 | + curr = curr.next |
| 51 | + temp = prev.data |
| 52 | + prev.data = start.data |
| 53 | + start.data = temp |
| 54 | + return prev |
| 55 | + |
| 56 | + |
| 57 | +# recursive quicksort for function calls |
| 58 | +def quicksort_LL(start, end): |
| 59 | + if start != end: |
| 60 | + pos = partition(start, end) |
| 61 | + quicksort_LL(start, pos) |
| 62 | + quicksort_LL(pos.next, end) |
| 63 | + return |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + ll = LinkedList() |
| 68 | + print("Enter the space seperated values of numbers to be inserted in linkedlist prompted below:") |
| 69 | + arr = list(map(int, input().split())) |
| 70 | + for num in arr: |
| 71 | + ll.insert(num) |
| 72 | + print("Linkedlist before sorting:") |
| 73 | + ll.printLL() |
| 74 | + quicksort_LL(ll.head, None) |
| 75 | + print('Linkedlist after sorting: ') |
| 76 | + ll.printLL() |
0 commit comments