-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path05_singlyLL_merge.py
102 lines (78 loc) · 1.98 KB
/
05_singlyLL_merge.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
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
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def prepend(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
cur_node = self.head
self.head = new_node
new_node.next = cur_node
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def merge_sorted(self, llist):
p = self.head
q = llist.head
s = None
if not p:
return q
if not q:
return p
if p and q:
if p.data <= q.data:
s = p
p = s.next
else:
s = q
q = s.next
new_head = s
while p and q:
if p.data <= q.data:
s.next = p
s = p
p = s.next
else:
s.next = q
s = q
q = s.next
if not p:
s.next = q
if not q:
s.next = p
return new_head
if __name__ == "__main__":
llist_1 = SinglyLinkedList()
llist_1.append(1)
llist_1.append(5)
llist_1.append(7)
llist_1.append(8)
llist_1.append(10)
llist_2 = SinglyLinkedList()
llist_2.append(2)
llist_2.append(3)
llist_2.append(4)
llist_2.append(6)
llist_2.append(9)
llist_1.print_list()
print("\n")
llist_2.print_list()
print("\n")
llist_1.merge_sorted(llist_2)
llist_1.print_list()