41
loading...
This website collects cookies to deliver better user experience
# Define empty stack
stack = []
# Add element to stack
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
stack.append(5)
print("Display stack after PUSH operation")
print(stack)
print("Remove element from stack")
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print("Display stack after POP operation")
print(stack)
Display stack after PUSH operation
[1, 2, 3, 4, 5]
Remove element from stack
5
4
3
2
1
Display stack after POP operation
[]
# Define empty stack
from collections import deque
stack = deque()
# Add element to stack
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
stack.append(5)
print("Display stack after PUSH operation")
print(stack)
print("Remove element from stack")
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print("Display stack after POP operation")
print(stack)
Display stack after PUSH operation
[1, 2, 3, 4, 5]
Remove element from stack
5
4
3
2
1
Display stack after POP operation
[]
# Define empty stack
from queue import LifoQueue
stack = LifoQueue(maxsize=5)
print(f"Size of stack: {stack.qsize()}")
# Add element to stack
stack.put(1)
stack.put(2)
stack.put(3)
stack.put(4)
stack.put(5)
print(f"Stack is Full: {stack.full()}")
print(f"Size of Stack: {stack.qsize()}")
print("Remove element from stack")
print(stack.get())
print(stack.get())
print(stack.get())
print(stack.get())
print(stack.get())
print(f"Stack is Empty: {stack.empty()}")
Size of stack: 0
Stack is Full: True
Size of Stack: 5
Remove element from stack
5
4
3
2
1
Stack is Empty: True
2 + 4 / 5 * (7 - 9)
by converting the expression to prefix or postfix form.Expression Conversion - Converting one form of expressions to another is one of the important applications of stacks.
Parenthesis Matching - Given an expression, you have to find if the parenthesis is either correctly matched or not. For example, consider the expression ( a + b ) * ( c + d
).
In the above expression, the opening and closing of the parenthesis are given properly and hence it is said to be a correctly matched parenthesis expression. Whereas, the expression, (a + b * [c + d )
is not a valid expression as the parenthesis are incorrectly given.
Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
In Graph Algorithms like Topological Sorting and Strongly Connected Components