Stacks
In computer science, a stack is an abstract data type that follows the Last-In, First-Out (LIFO) principle. Think of a stack of dishes. You can only add a new dish to the top of the stack, and you can only remove the dish that is currently on the top.
Stacks are commonly used to implement algorithms that require a last-in, first-out order. For example, function calls in a program are often stored in a stack. When a function is called, its information is pushed onto the stack, and when the function returns, its information is popped from the stack.
Here is an example of creating and manipulating a stack using a list in Python:
PYTHON
1if __name__ == '__main__':
2 # Create a stack using a list
3 stack = []
4
5 # Add elements to the stack
6 stack.append('A')
7 stack.append('B')
8 stack.append('C')
9
10 # Print the stack
11 print('Stack:', stack)
12
13 # Remove elements from the stack
14 print('Popped:', stack.pop())
15 print('Popped:', stack.pop())
16
17 # Print the stack after popping
18 print('Stack:', stack)xxxxxxxxxx36
print('Queue:', queue)if __name__ == '__main__': # Create a stack using a list stack = [] # Add elements to the stack stack.append('A') stack.append('B') stack.append('C') # Print the stack print('Stack:', stack) # Remove elements from the stack print('Popped:', stack.pop()) print('Popped:', stack.pop()) # Print the stack after popping print('Stack:', stack) # Create a queue using a list queue = [] # Add elements to the queue queue.append('X') queue.append('Y') queue.append('Z') # Print the queue print('Queue:', queue)OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


