1class Node:
2 def __init__(self, x, nextNode = None):
3 self.val = x
4 self.next = nextNode
5
6def printList(l):
7 value = []
8 while(l):
9 value.append(l.val)
10 l = l.next
11 print(' -> '.join(map(str, value)))
12
13def addTwoNumbers(l1, l2):
14 """
15 :type l1: Node
16 :type l2: Node
17 :rtype: Node
18 """
19 sum = l1.val + l2.val
20 carry = int(sum / 10)
21
22 l3 = Node(sum%10)
23 p1 = l1.next
24 p2 = l2.next
25 p3 = l3
26 while(p1 != None or p2 != None):
27 sum = carry + ( p1.val if p1 else 0) + ( p2.val if p2 else 0)
28 carry = int(sum/10)
29 p3.next = Node(sum % 10)
30 p3 = p3.next
31 p1 = p1.next if p1 else None
32 p2 = p2.next if p2 else None
33
34 if(carry > 0):
35 p3.next = Node(carry)
36
37 return l3
38
39#789
40l1 = Node(9, Node(8, Node(7)))
41printList(l1)
42#478
43l2 = Node(8, Node(7, Node(4)))
44printList(l2)
45l3 = addTwoNumbers(l1, l2)
46printList(l3)
47print()
48#342
49l1 = Node(2, Node(4, Node(3)))
50printList(l1)
51#465
52l2 = Node(5, Node(6, Node(4)))
53printList(l2)
54l3 = addTwoNumbers(l1, l2)
55printList(l3)
1class SinglyLinkedListNode:
2 def __init__(self, node_data):
3 self.data = node_data
4 self.next = None
5
6
7class SinglyLinkedList:
8 def __init__(self):
9 self.head = None
10 self.tail = None
11
12 def insert_node(self, node_data):
13 node = SinglyLinkedListNode(node_data)
14
15 if not self.head:
16 self.head = node
17 else:
18 self.tail.next = node
19
20 self.tail = node
21
22
23def print_singly_linked_list(node, sep):
24 while node:
25 print(str(node.data), end=' ')
26
27 node = node.next
28
29
30def printt(headd):
31 itr = headd
32 llstr = []
33 while itr:
34 llstr.append(itr.data)
35 itr = itr.next
36 return llstr
37
38
39def mergeLists(llist1, llist2):
40 ll1 = printt(llist1)
41 ll2 = printt(llist2)
42 ll3 = (ll1 + ll2)
43 ll3.sort()
44 lll = SinglyLinkedList()
45 for ii in ll3:
46 lll.insert_node(ii)
47 return lll.head
48
49
50if __name__ == '__main__':
51
52 llist1_count = int(
53 input("Enter the number of element to be in linked list 1: "))
54
55 llist1 = SinglyLinkedList()
56
57 print("Enter the elements to be added in list1 line by line")
58 for _ in range(llist1_count):
59 llist1_item = int(input())
60 llist1.insert_node(llist1_item)
61
62 print("\n")
63 llist2_count = int(
64 input("Enter the number of element to be in linked list 2: "))
65
66 llist2 = SinglyLinkedList()
67
68 print("Enter the elements to be added in list2 line by line")
69 for _ in range(llist2_count):
70 llist2_item = int(input())
71 llist2.insert_node(llist2_item)
72
73 llist3 = mergeLists(llist1.head, llist2.head)
74
75 print("\n")
76 print("The merged linked list value: ")
77 print_singly_linked_list(llist3, ' ')
78
79'''
80Output window:
81Enter the number of element to be in linked list 1: 3
82Enter the elements to be added in list1 line by line
831
842
853
86Enter the number of element to be in linked list 2: 2
87Enter the elements to be added in list2 line by line
883
894
90The merged linked list value:
911 2 3 3 4
92'''