Stack:
Case1:
class Stack:
def __init__(self):
[Link] = []
def is_empty(self):
return len([Link]) == 0
def push(self, item):
[Link](item)
print("pushed item:", item)
def pop(self):
if self.is_empty():
return "stack is empty"
return [Link]()
def display(self):
print("stack after popping an element:", [Link])
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):
[Link] = []
def push(self, item):
[Link](item)
print("Pushed:", item)
def pop(self):
return [Link]() if [Link] else "Stack is empty"
def display(self):
print("Stack:", [Link] if [Link] 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:
Operators = set(['+', '-', '*', '/', '(', ')', '^'])
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3}
def infixToPostfix(expression):
stack = []
output = ''
for character in expression:
if character not in Operators:
output+= character
elif character=='(':
[Link]('(')
elif character==')':
while stack and stack[-1]!= '(':
output+=[Link]()
[Link]()
else:
while stack and stack[-1]!='(' and Priority[character]<=Priority[stack[-1]]:
output+=[Link]()
[Link](character)
while stack:
output+=[Link]()
return output
expression = input('Enter infix expression ')
print('infix notation: ',expression)
print('postfix notation: ',infixToPostfix(expression))
Queue:
class Queue():
def __init__(self, k):
self.k = k
[Link] = [None] * k
[Link] = [Link] = -1
def enqueue(self, data):
if ([Link] == self.k - 1):
print("The queue is full\n")
elif ([Link] == -1):
[Link] = 0
[Link] = 0
[Link][[Link]] = data
else:
[Link] = [Link] + 1
[Link][[Link]] = data
def dequeue(self):
if ([Link] == -1):
print("The queue is empty\n")
elif ([Link] == [Link]):
temp = [Link][[Link]]
[Link] = -1
[Link] = -1
return temp
else:
temp = [Link][[Link]]
[Link] = [Link] + 1
return temp
def printQueue(self):
if([Link] == -1):
print("No element in the queue")
else:
for i in range([Link], [Link] + 1):
print([Link][i], end=" ")
print()
obj = Queue(5)
[Link](1)
[Link](2)
[Link](3)
[Link](4)
[Link](5)
print("Initial queue")
[Link]()
[Link]()
print("After removing an element from the queue")
[Link]()