Stack & Queue
Stack & Queue
Case1:
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def pop(self):
if self.is_empty():
return "stack is empty"
return self.stack.pop()
def display(self):
print("stack after popping an element:", self.stack)
my_stack = Stack()
my_stack.push(1)
my_stack.push(2)
my_stack.push(3)
print("popped item:", my_stack.pop())
my_stack.display()
case2:
class Stack:
def __init__(self):
self.stack = []
def pop(self):
return self.stack.pop() if self.stack else "Stack is empty"
def display(self):
print("Stack:", self.stack if self.stack else "Empty stack")
my_stack = Stack()
while True:
choice = input("\n1: Push | 2: Pop | 3: Display | 4: Exit\nChoose: ")
if choice == '1':
my_stack.push(int(input("Enter item: ")))
elif choice == '2':
print("Popped:", my_stack.pop())
elif choice == '3':
my_stack.display()
elif choice == '4':
break
else:
print("Invalid choice!")
Infix to Postfix:
def infixToPostfix(expression):
stack = []
output = ''
elif character=='(':
stack.append('(')
elif character==')':
output+=stack.pop()
stack.pop()
else:
output+=stack.pop()
stack.append(character)
while stack:
output+=stack.pop()
return output
Queue:
class Queue():
def dequeue(self):
if (self.head == -1):
print("The queue is empty\n")
def printQueue(self):
if(self.head == -1):
print("No element in the queue")
else:
for i in range(self.head, self.tail + 1):
print(self.queue[i], end=" ")
print()
obj = Queue(5)
obj.enqueue(1)
obj.enqueue(2)
obj.enqueue(3)
obj.enqueue(4)
obj.enqueue(5)
print("Initial queue")
obj.printQueue()
obj.dequeue()
print("After removing an element from the queue")
obj.printQueue()