-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathMerge Sort for a linked list
More file actions
125 lines (74 loc) Β· 2.03 KB
/
Copy pathMerge Sort for a linked list
File metadata and controls
125 lines (74 loc) Β· 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
from sys import stdin, setrecursionlimit
setrecursionlimit(10 ** 6)
#Following is the Node class already written for the Linked List
class Node :
def __init__(self, data) :
self.data = data
self.next = None
def sortedMerge(a,b):
result = None
# Base cases
if a == None:
return b
if b == None:
return a
# pick either a or b and recur..
if a.data <= b.data:
result = a
result.next = sortedMerge(a.next, b)
else:
result = b
result.next = sortedMerge(a, b.next)
return result
def getMiddle(head):
if (head == None):
return head
slow = head
fast = head
while (fast.next != None and
fast.next.next != None):
slow = slow.next
fast = fast.next.next
return slow
def mergeSort(head) :
#Your code goes here
# Base case if head is None
if head == None or head.next == None:
return head
# get the middle of the list
middle = getMiddle(head)
nexttomiddle = middle.next
# set the next of middle node to None
middle.next = None
# Apply mergeSort on left list
left = mergeSort(head)
# Apply mergeSort on right list
right = mergeSort(nexttomiddle)
# Merge the left and right lists
sortedlist = sortedMerge(left, right)
return sortedlist
#Taking Input Using Fast I/O
def takeInput() :
head = None
tail = None
datas = list(map(int, stdin.readline().rstrip().split(" ")))
i = 0
while (i < len(datas)) and (datas[i] != -1) :
data = datas[i]
newNode = Node(data)
if head is None :
head = newNode
tail = newNode
else :
tail.next = newNode
tail = newNode
i += 1
return head
def printLinkedList(head) :
while head is not None :
print(head.data, end = " ")
head = head.next
print()
head = takeInput()
newHead = mergeSort(head)
printLinkedList(newHead)