Skip to content

Commit fc71700

Browse files
authored
Update merge_two_sorted_linkedlist.py
1 parent 3a79c2c commit fc71700

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Data Structures/Linked Lists/Singly Linked List/merge_two_sorted_linkedlist.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1+
# Class for creating nodes in linkedlist
12
class SinglyLinkedListNode:
23
def __init__(self, node_data):
34
self.data = node_data
45
self.next = None
56

6-
7+
#Class for building linkedlist
78
class SinglyLinkedList:
89
def __init__(self):
910
self.head = None
1011
self.tail = None
11-
12+
13+
#Function for inserting node
1214
def insert_node(self, node_data):
1315
node = SinglyLinkedListNode(node_data)
1416

@@ -19,14 +21,14 @@ def insert_node(self, node_data):
1921

2022
self.tail = node
2123

22-
24+
#Function to print the linked list
2325
def print_singly_linked_list(node, sep):
2426
while node:
2527
print(str(node.data), end=' ')
2628

2729
node = node.next
2830

29-
31+
# Function for getting elements in first and second linked list in array
3032
def printt(headd):
3133
itr = headd
3234
llstr = []
@@ -36,17 +38,18 @@ def printt(headd):
3638
return llstr
3739

3840

41+
# This function takes two linked list and compares it and merge two list
3942
def mergeLists(llist1, llist2):
4043
ll1 = printt(llist1)
4144
ll2 = printt(llist2)
42-
ll3 = (ll1 + ll2)
45+
ll3 = (ll1 + ll2) #comparing and merging two linked list
4346
ll3.sort()
44-
lll = SinglyLinkedList()
47+
lll = SinglyLinkedList() #creating new linkedlist
4548
for ii in ll3:
46-
lll.insert_node(ii)
49+
lll.insert_node(ii) #Adding merged element to new linked list
4750
return lll.head
4851

49-
52+
# Main funcation
5053
if __name__ == '__main__':
5154

5255
llist1_count = int(
@@ -95,4 +98,7 @@ def mergeLists(llist1, llist2):
9598
The merged linked list value:
9699
1 2 3 3 4
97100
101+
Complexity:
102+
Time complexity: O(n)
103+
Space complexity: O(n)
98104
'''

0 commit comments

Comments
 (0)