-
Notifications
You must be signed in to change notification settings - Fork 222
/
merge-two-sorted-linked-lists.py
61 lines (38 loc) · 1.11 KB
/
merge-two-sorted-linked-lists.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
"""
Merge two linked lists
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def Insert(head, data):
node = head
if head is None:
head = Node(data)
return head
while node.next is not None:
node = node.next
node.next = Node(data)
return head
def MergeLists(headA, headB):
list_out = Node()
node_a = headA
node_b = headB
while node_a and node_b:
if node_a.data < node_b.data:
list_out = Insert(list_out, node_a.data)
node_a = node_a.next
else:
list_out = Insert(list_out, node_b.data)
node_b = node_b.next
last_node = list_out
while last_node.next is not None:
last_node = last_node.next
if node_a:
last_node.next = node_a
elif node_b:
last_node.next = node_b
return list_out.next