Skip to content

Commit d4772be

Browse files
committed
append and prepend
1 parent c590fb1 commit d4772be

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

create_linked_list.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# we had created a node here which has data and a pointer which points towards none for now
1+
# we had created a node
22
class Node:
33
def __init__(self, data):
44
self.data = data
@@ -14,19 +14,33 @@ def __init__(self):
1414

1515
def printList(self): # the function that will print the list
1616
temp = self.head
17-
while temp.next is not None:
17+
while temp:
1818
print(temp.data)
1919
temp = temp.next
2020

21+
def append(self, data):
22+
new_node = Node(data)
23+
if self.head is None:
24+
self.head = new_node
25+
return
26+
temp = self.head
27+
while temp.next:
28+
temp = temp.next
29+
temp.next = new_node
30+
31+
def prepend(self, data):
32+
new_node = Node(data)
33+
if not self.head:
34+
self.head = new_node
35+
return
36+
else:
37+
new_node.next = self.head
38+
self.head = new_node
39+
2140

22-
# we have created the list here
2341
l1 = Linked_list()
24-
l1.head = Node(100)
25-
l2 = Node(200)
26-
l3 = Node(300)
27-
l4 = Node(400)
28-
# we have link the list with each other
29-
l1.head.next = l2
30-
l2.next = l3
31-
l3.next = l4
42+
l1.append(100)
43+
l1.append(200)
44+
l1.prepend(10)
45+
l1.prepend(20)
3246
l1.printList()

0 commit comments

Comments
 (0)