-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmergeLinkedList.py
67 lines (51 loc) · 1.29 KB
/
mergeLinkedList.py
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
class node:
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(temp.data, end="->")
temp = temp.next
def append(self, newData):
newNode = node(newData)
if self.head is None:
self.head = newNode
return
last = self.head
while last.next:
last = last.next
last.next = newNode
def mergeList(head1, head2):
temp = None
if head1 is None:
return head2
if head2 is None:
return head1
if head1.data <= head2.data:
temp = head1
temp.next = mergeList(head1.next, head2)
else:
temp = head2
temp.next = mergeList(head1, head2.next)
return temp
if __name__ == "__main__":
list1 = linkedList()
list1.append(10)
list1.append(20)
list1.append(30)
list1.append(40)
list1.append(50)
list2 = linkedList()
list2.append(5)
list2.append(15)
list2.append(18)
list2.append(35)
list2.append(80)
list3 = linkedList()
list_dat = mergeList(list1.head, list2.head)
print("merge linked list is : ", end="")
list3.printList()