Skip to content

Commit b886da8

Browse files
authored
Create Stack_Linked_List.py
1 parent 5214b7c commit b886da8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
class Node: # Class to create Nodes
2+
def __init__(self, Value, Next=None):
3+
self.value = Value # value in Node
4+
self.next = Next # points to next node
5+
6+
class Stack_LL:
7+
def __init__(self):
8+
self.__top = None # initially top = None
9+
self.__len = 0 # initially length of stack = 0
10+
11+
def is_empty(self):
12+
return self.__top == None
13+
14+
def push(self, value):
15+
self.__top = Node(value, self.__top) # Create Node with value = "value" & next = "top". Make new node as top
16+
self.__len += 1 # increment length
17+
18+
def pop(self):
19+
if(self.is_empty()): raise IndexError("Stack is Empty") # check if stack is empty
20+
else:
21+
temp = self.__top # temp = top
22+
self.__top = self.__top.next # top = next element
23+
temp.next = None # (previous top) temp.next -> None (break the link)
24+
self.__len -= 1 # decrement length
25+
return temp.value # return poped value
26+
27+
def __len__(self):
28+
return self.__len
29+
30+
def __str__(self): # return str form of linked list i.e., val1 -> val2 -> None
31+
temp = self.__top
32+
Values = []
33+
while temp:
34+
Values.append(str(temp.value)) # add values to "Values"
35+
temp = temp.next
36+
Values.append("None")
37+
return " -> ".join(Values) # return all Values as string
38+
39+
# __next__ and __iter__ methods are used to iterate through the object
40+
41+
# __next__ is used to get the next element in the iterable object
42+
def __next__(self):
43+
temp = self.__i
44+
if (temp == None): raise StopIteration() # if temp = None, temp has reached the end, raise StopIteration to stop iteration
45+
self.__i = self.__i.next
46+
return temp.value
47+
48+
# __iter__ returns an iterable object (self) & sets i = top, to iterate through top to end
49+
def __iter__(self):
50+
self.__i = self.__top
51+
return self
52+
53+
if __name__ == '__main__':
54+
S1 = Stack_LL()
55+
56+
for i in range(5, 21, 5):
57+
print("push", i, "to stack")
58+
S1.push(i)
59+
60+
print("\nStack : ", S1)
61+
62+
print("\nPop stack, popped value = ", S1.pop())

0 commit comments

Comments
 (0)