File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ # A-2:Linked List implementation of Stack(Linked implementation)
2
+
3
+ class StackEmptyError(Exception):
4
+ pass
5
+
6
+ class Node:
7
+ def __init__(self,value):
8
+ self.data=value
9
+ self.link=None
10
+
11
+ class Stack:
12
+ def __init__(self):
13
+ self.top=None
14
+ def is_empty(self):
15
+ return self.top==None
16
+ def size(self):
17
+ if self.is_empty():
18
+ return 0
19
+ count=0
20
+ p=self.top
21
+ while p is not None:
22
+ count+=1
23
+ p=p.link
24
+ return count
25
+ def push(self,data):
26
+ temp=Node(data)
27
+ temp.link=self.top
28
+ self.top=temp
29
+ def pop(self):
30
+ if self.is_empty():
31
+ raise StackEmptyError("List is Empty, can't pop!!")
32
+ popped_ele=self.top.data
33
+ self.top=self.top.link
34
+ return popped_ele
35
+ def peek(self):
36
+ if self.is_empty():
37
+ raise StackEmptyError("List is empty!!")
38
+ return self.top.data
39
+ def display(self):
40
+ if self.is_empty():
41
+ print("Empty list")
42
+ return
43
+ print("List is: ")
44
+ p=self.top
45
+ while p is not None:
46
+ print(p.data,end=" ")
47
+ p=p.link
48
+
49
+ if __name__=="__main__":
50
+ stack=Stack()
51
+
52
+ while True:
53
+ print("1.Push.")
54
+ print("2.Pop.")
55
+ print("3.Peek.")
56
+ print("4.Size.")
57
+ print("5.Display.")
58
+ print("6.Quit")
59
+
60
+ choice=int(input("Enter a choice: "))
61
+ if(choice==1):
62
+ ele=int(input("Enter the elements: "))
63
+ stack.push(ele)
64
+ elif(choice==2):
65
+ popped=stack.pop()
66
+ print("Popped element is : ",popped)
67
+ elif(choice==3):
68
+ print("Element at the top is : ",stack.peek())
69
+ elif(choice==4):
70
+ print("Size of the stack is: ",stack.size())
71
+ elif(choice==5):
72
+ stack.display()
73
+ elif(choice==6):
74
+ break
75
+ else:
76
+ print("Invalid choice!!")
77
+ print()
You can’t perform that action at this time.
0 commit comments