1
+ # Class for creating nodes in linkedlist
1
2
class SinglyLinkedListNode :
2
3
def __init__ (self , node_data ):
3
4
self .data = node_data
4
5
self .next = None
5
6
6
-
7
+ #Class for building linkedlist
7
8
class SinglyLinkedList :
8
9
def __init__ (self ):
9
10
self .head = None
10
11
self .tail = None
11
-
12
+
13
+ #Function for inserting node
12
14
def insert_node (self , node_data ):
13
15
node = SinglyLinkedListNode (node_data )
14
16
@@ -19,14 +21,14 @@ def insert_node(self, node_data):
19
21
20
22
self .tail = node
21
23
22
-
24
+ #Function to print the linked list
23
25
def print_singly_linked_list (node , sep ):
24
26
while node :
25
27
print (str (node .data ), end = ' ' )
26
28
27
29
node = node .next
28
30
29
-
31
+ # Function for getting elements in first and second linked list in array
30
32
def printt (headd ):
31
33
itr = headd
32
34
llstr = []
@@ -36,17 +38,18 @@ def printt(headd):
36
38
return llstr
37
39
38
40
41
+ # This function takes two linked list and compares it and merge two list
39
42
def mergeLists (llist1 , llist2 ):
40
43
ll1 = printt (llist1 )
41
44
ll2 = printt (llist2 )
42
- ll3 = (ll1 + ll2 )
45
+ ll3 = (ll1 + ll2 ) #comparing and merging two linked list
43
46
ll3 .sort ()
44
- lll = SinglyLinkedList ()
47
+ lll = SinglyLinkedList () #creating new linkedlist
45
48
for ii in ll3 :
46
- lll .insert_node (ii )
49
+ lll .insert_node (ii ) #Adding merged element to new linked list
47
50
return lll .head
48
51
49
-
52
+ # Main funcation
50
53
if __name__ == '__main__' :
51
54
52
55
llist1_count = int (
@@ -95,4 +98,7 @@ def mergeLists(llist1, llist2):
95
98
The merged linked list value:
96
99
1 2 3 3 4
97
100
101
+ Complexity:
102
+ Time complexity: O(n)
103
+ Space complexity: O(n)
98
104
'''
0 commit comments