Computer Science
Write a program that, depending upon the user's choice, either adds or removes an element from a Stack.
Answer
def add(stack):
h = input("Enter element: ")
stack.append(h)
def remove(stack):
if len(stack) == 0:
print("No element to delete")
else:
print("Deleted element is:", stack.pop())
stack = []
while True:
print("1. Add element")
print("2. Delete element")
print("3. Exit")
op = int(input("Enter the Choice: "))
if op == 1:
add(stack)
elif op == 2:
remove(stack)
elif op == 3:
print("Exiting program.")
breakOutput
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 11
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 33
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 44
1. Add element
2. Delete element
3. Exit
Enter the Choice: 2
Deleted element is: 44
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 55
1. Add element
2. Delete element
3. Exit
Enter the Choice: 2
Deleted element is: 55
1. Add element
2. Delete element
3. Exit
Enter the Choice: 3
Exiting program.
Related Questions
Write an algorithm to insert element into Queue as a list.
Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user. Display the content of the Stack along with the largest odd number in the Stack. (Hint. Keep popping out the elements from stack and maintain the largest element retrieved so far in a variable. Repeat till Stack is empty)
Write a program that, depending upon the user's choice, either pushes or pops an element in a Stack. The elements are shifted towards the right so that the top always remains at 0th (zeroth) index.
Write a program to insert or delete an element from a Queue depending upon the user's choice. The elements are not shifted after insertion or deletion.