forked from akkupy/codeDump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_using_list.py
80 lines (70 loc) · 2.05 KB
/
stack_using_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# menu driven python program for implementation of stack using list
# program contains push,pop,display,peek functions
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, data):
new_node = Node(data)
if self.is_empty():
self.top = new_node
else:
new_node.next = self.top
self.top = new_node
def pop(self):
if self.is_empty():
print("Stack is empty")
else:
popped_item = self.top.data
self.top = self.top.next
return popped_item
def peek(self):
if self.is_empty():
print("Stack is empty")
else:
return self.top.data
def display(self):
current = self.top
if current is None:
print("Stack is empty")
else:
print("Stack:")
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
def main():
stack = Stack()
while True:
print("\nStack Menu:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Quit")
choice = input("Enter your choice: ")
if choice == '1':
data = input("Enter data to push onto the stack: ")
stack.push(data)
elif choice == '2':
popped_item = stack.pop()
if popped_item is not None:
print("Popped item:", popped_item)
elif choice == '3':
peeked_item = stack.peek()
if peeked_item is not None:
print("Top item:", peeked_item)
elif choice == '4':
stack.display()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()