Merge two sorted linked lists in python
Python program for Merge two sorted linked lists. Here problem description and other solutions.
# Python 3 program for
# Merge two sorted lists
# Linked list node
class LinkNode :
def __init__(self, data) :
self.data = data
self.next = None
class SingleLL :
def __init__(self) :
self.head = None
self.tail = None
# Add new node at end of linked list
def addNode(self, data) :
node = LinkNode(data)
if (self.head == None) :
self.head = node
else :
# Append the node at last position
self.tail.next = node
self.tail = node
# Display linked list element
def display(self) :
if (self.head == None) :
print("\n Empty linked list")
return
temp = self.head
# iterating linked list elements
while (temp != None) :
print("", temp.data , end = " →")
# Visit to next node
temp = temp.next
print(" NULL")
# Sorted Merge of two sorted list
def mergeList(self, other) :
if (other.head == None) :
# When have no element in second linked list
return
elif (self.head == None) :
self.head = other.head
self.tail = other.tail
else :
# Define some useful resultant variable
n1 = self.head
n2 = other.head
auxiliary = None
# Reset resultant list
self.head = None
self.tail = None
# iterate linked list element
while (n1 != None or n2 != None) :
if (n1 != None and n2 != None) :
# Compare front node element of both linked list
if (n1.data <= n2.data) :
# Get front node of first linked list
auxiliary = n1
# Visit to next node
n1 = n1.next
else :
# Get front node of second linked list
auxiliary = n2
# Visit to next node
n2 = n2.next
elif (n1 != None) :
auxiliary = n1
# Visit to next node
n1 = n1.next
else :
auxiliary = n2
# Visit to next node
n2 = n2.next
if (self.head == None) :
# First node of resultant linked list
self.head = auxiliary
self.tail = auxiliary
else :
# Add node at last of resultant list
self.tail.next = auxiliary
# Set new last node
self.tail = auxiliary
other.head = None
other.tail = None
def main() :
# Create linked list
sll1 = SingleLL()
sll2 = SingleLL()
# Sorted linked list 1
# 1 → 7 → 8 → 15 → 19 → NULL
sll1.addNode(1)
sll1.addNode(7)
sll1.addNode(8)
sll1.addNode(15)
sll1.addNode(19)
# Sorted linked list 2
# -2 → 5 → 6 → 12 → 16 → 18 → 19 → 31 → NULL
sll2.addNode(-2)
sll2.addNode(5)
sll2.addNode(6)
sll2.addNode(12)
sll2.addNode(16)
sll2.addNode(18)
sll2.addNode(19)
sll2.addNode(31)
print("\n First Linked List")
sll1.display()
print(" Second Linked List")
sll2.display()
sll1.mergeList(sll2)
# -2 → 1 → 5 → 6 → 7 → 8 → 12 → 15 → 16
# → 18 → 19 → 19 → 31 → NULL
print(" After Merge")
sll1.display()
if __name__ == "__main__": main()
Output
First Linked List
1 → 7 → 8 → 15 → 19 → NULL
Second Linked List
-2 → 5 → 6 → 12 → 16 → 18 → 19 → 31 → NULL
After Merge
-2 → 1 → 5 → 6 → 7 → 8 → 12 → 15 → 16 → 18 → 19 → 19 → 31 → NULL
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment