0% found this document useful (0 votes)
2 views

Stack

The document provides a Python implementation of a basic stack data structure with operations such as push, pop, peek, and display. It includes a user interface that allows users to interact with the stack through a menu-driven approach. The code handles empty stack scenarios and provides feedback for each operation performed.

Uploaded by

dhevsooriya007
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Stack

The document provides a Python implementation of a basic stack data structure with operations such as push, pop, peek, and display. It includes a user interface that allows users to interact with the stack through a menu-driven approach. The code handles empty stack scenarios and provides feedback for each operation performed.

Uploaded by

dhevsooriya007
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Stack –Basic Operation

Source Code:
class Stack:
def init (self):
self.items = []

def is_empty(self):
return len(self.items) == 0

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()
else:
print("Stack is empty, cannot pop from an empty stack")
return None

def peek(self):
if not self.is_empty():
return self.items[-1]
else:
print("Stack is empty, cannot peek from an empty stack")
return None

def display(self):
if not self.is_empty():
print(self.items)
else:
print("Stack is empty")

stack = Stack()

while True: print("\


n1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
item = input("Enter the item to push: ")
stack.push(item)
elif choice == 2:
popped_item = stack.pop()
if popped_item is not None:
print("Popped item:", popped_item)
elif choice == 3:
top_item = stack.peek()
if top_item is not None:
print("Top item:", top_item)
elif choice == 4:
stack.display()
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the item to push: 03

1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the item to push: 18

1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the item to push: 07

1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
['03', '18', '07']

1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 2
Popped item: 07
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 3
Top item: 18
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
['03', '18']

1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 5
Exiting the program.

You might also like