# 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

def __init__(self, data) :
self.data = data
self.next = None

class SingleLL :
def __init__(self) :
self.tail = None

else :
#  Append the node at last position
self.tail.next = node

self.tail = node

def display(self) :
return

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) :
#  When have no element in second linked list
return
self.tail = other.tail
else :
#  Define some useful resultant variable
auxiliary = None
#  Reset resultant list
self.tail = None
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

#  First node of resultant linked list
self.tail = auxiliary
else :
#  Add node at last of resultant list
self.tail.next = auxiliary
#  Set new last node
self.tail = auxiliary

other.tail = None

def main() :
sll1 = SingleLL()
sll2 = SingleLL()
#   1 → 7 → 8 → 15 → 19 → NULL
#   -2 → 5 → 6 → 12 → 16 → 18 → 19 → 31 → NULL
sll1.display()
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