Skip to content

Commit 8b47d9a

Browse files
Added comments and complexity
1 parent 5f3e6d9 commit 8b47d9a

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

Data Structures/Linked Lists/Singly Linked List/Single-linked-list-operations.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
1+
// A pythom program for all operations performed on singly linked-list.
2+
// Time-Complexity = O(n)
3+
// Space-Complexity = O(n)
14
class Node:
2-
def __init__(self, data=None, next=None):
5+
def __init__(self, data=None, next=None): // Creation of Node
36
self.data = data
47
self.next = next
58

69
class LinkedList:
710
def __init__(self):
8-
self.head = None
11+
self.head = None // head points the first node
912

1013
def print(self):
1114
if self.head is None:
1215
print("Linked list is empty")
1316
return
1417
itr = self.head
15-
llstr = ''
18+
llstr = '' // empty string
1619
while itr:
1720
llstr += str(itr.data)+' --> ' if itr.next else str(itr.data)
1821
itr = itr.next
1922
print(llstr)
2023

21-
def length(self):
24+
def length(self): // will calculate length of the linked list
2225
count = 0
2326
itr = self.head
2427
while itr:
@@ -28,7 +31,7 @@ def length(self):
2831
return count
2932

3033
def insert_at_begining(self, data):
31-
node = Node(data, self.head)
34+
node = Node(data, self.head) // Creating a new node calling Node method
3235
self.head = node
3336

3437
def insert_at_end(self, data):
@@ -74,7 +77,7 @@ def remove_at(self, index):
7477
itr = self.head
7578
while itr:
7679
if count == index - 1:
77-
itr.next = itr.next.next
80+
itr.next = itr.next.next // to delete the specified node
7881
break
7982

8083
itr = itr.next
@@ -94,4 +97,4 @@ def insert_values(self, data_list):
9497
node1.print()
9598
node1.insert_values([45,7,12,567,99])
9699
node1.insert_at_end(67)
97-
node1.print()
100+
node1.print()

0 commit comments

Comments
 (0)