push
in a stack is putting an item on top of the stack.
pop
in a stack is taking out the top item in the stack.
Stacks are used extensively in a lot of places.
Compilers and Parsers – Expression evaluation is done by stacks by postfix or prefix using stacks in compilers.
Activation Records – An activation record is data that keeps track of the procedure activities during the runtime of a program.
When the function is called, an activation record is created for it and keeps track of parameters and information like local variables, return address, static and dynamic links, and the return value.
This activation record is the fundamental part of programming languages and is implemented using a stack.
Web Browsers – Web Browsers use a stack to keep track of URLs that you have visited previously. When you visit a new page, it is added to the stack and when you hit the back button, the stack is popped and the previous URL is accessed.
To implement other Data Structures – Stacks are used to implement searches in Graphs and Trees, which are other complex data structures.
Stack Methods
There are various functions that are associated with a stack. They are,
stack.isEmpty()
The stack.isEmpty()
method returns True
if the stack is empty. Else, returns False
Time Complexity - O(1)
stack.length()
The stack.length()
method returns the length of the stack.
Time Complexity - O(1)
stack.top()
The stack.top()
method returns a pointer/reference to the top element in the stack.
Time Complexity - O(1)
stack.push(x)
The stack.push()
method inserts the element, x
to the top of the stack.
Time Complexity - O(1)
stack.pop()
The stack.pop()
method removes the top element of the stack and returns it.
Time Complexity - O(1)
In Python, we can implement the stack by various methods. We are going to dive into two of the methods - the common method and the efficient method.
We use the list methods append
and pop
to implement a Stack.
Python collections
are container classes that are used for data collection storage. They are highly optimized, are really fast, and have lots of methods built-in.
Deque
is one such python collection that is used for inserting and removing items. We can use it to create a faster implementation of a stack.
Once you are done with understanding the stack and the basic implementation, practice the following problems and problem-sets in order to get a strong grasp on stacks.
Infix to Postfix - GeeksForGeeks
Next Greater Element - GeeksForGeeks
Postfix to Prefix - GeeksForGeeks
Reverse a String using Stack - GeeksForGeeks
Mini Parser - LeetCode
Simplify Path - LeetCode
More Stack Problems - LeetCode
Stack Problem Set - HackerRank
We have learned the implementation, importance, and application of stacks. This is one of the most important data structures to know and it is extensively asked in the computer science industry. It is important to have strong knowledge on this topic as it would give you an edge.
A great analogy we can use is stacking a pile of books. We always keep a new book on top and remove the topmost book. Stacks are similar to queues in that they are linear collections of items, but they differ in the order in which they are accessed. Stacks are used in a variety of areas from Operating System Software, in Compilers and Language Parsing, and to implement other complex Data Structures like Trees and Graphs.
Unlike an array structure, which allows random access at all the positions, a stack limits the inserting and removing operation to only one side of the data sequence. A stack follows the last in, first out (LIFO) principle.
In Python, stack can be implemented using a list. To follow the LIFO principle, inserting and removing operations both occur at the tail of the list.Python implementation of a stack
pop
in a stack is taking out the top item in the stack.
Stacks are used extensively in a lot of places.
Compilers and Parsers – Expression evaluation is done by stacks by postfix or prefix using stacks in compilers.
Activation Records – An activation record is data that keeps track of the procedure activities during the runtime of a program.
When the function is called, an activation record is created for it and keeps track of parameters and information like local variables, return address, static and dynamic links, and the return value.
This activation record is the fundamental part of programming languages and is implemented using a stack.
Web Browsers – Web Browsers use a stack to keep track of URLs that you have visited previously. When you visit a new page, it is added to the stack and when you hit the back button, the stack is popped and the previous URL is accessed.
To implement other Data Structures – Stacks are used to implement searches in Graphs and Trees, which are other complex data structures.
Stack Methods
There are various functions that are associated with a stack. They are,
stack.isEmpty()
The stack.isEmpty()
method returns True
if the stack is empty. Else, returns False
Time Complexity - O(1)
stack.length()
The stack.length()
method returns the length of the stack.
Time Complexity - O(1)
stack.top()
The stack.top()
method returns a pointer/reference to the top element in the stack.
Time Complexity - O(1)
stack.push(x)
The stack.push()
method inserts the element, x
to the top of the stack.
Time Complexity - O(1)
stack.pop()
The stack.pop()
method removes the top element of the stack and returns it.
Time Complexity - O(1)
In Python, we can implement the stack by various methods. We are going to dive into two of the methods - the common method and the efficient method.
We use the list methods append
and pop
to implement a Stack.
Python collections
are container classes that are used for data collection storage. They are highly optimized, are really fast, and have lots of methods built-in.
Deque
is one such python collection that is used for inserting and removing items. We can use it to create a faster implementation of a stack.
Once you are done with understanding the stack and the basic implementation, practice the following problems and problem-sets in order to get a strong grasp on stacks.
Infix to Postfix - GeeksForGeeks
Next Greater Element - GeeksForGeeks
Postfix to Prefix - GeeksForGeeks
Reverse a String using Stack - GeeksForGeeks
Mini Parser - LeetCode
Simplify Path - LeetCode
More Stack Problems - LeetCode
Stack Problem Set - HackerRank
We have learned the implementation, importance, and application of stacks. This is one of the most important data structures to know and it is extensively asked in the computer science industry. It is important to have strong knowledge on this topic as it would give you an edge.
Implementation of an interpreter for a small language that does multiplication/addition/etc.
Design a MinStack
data structure that supports a min()
operation that returns the minimum value in the stack in O(1) time.
Write an algorithm to determine if all of the delimiters in an expression are matched and closed.
E.g. {ac[bb]}
, [dklf(df(kl))d]{}
and {[[[]]]}
are matched. But {3234[fd
and {df][d}
are not.
Sort a stack in ascending order using an additional stack.
Many developers imagine stacks as a stack of dinner plates; you can add or remove plates to the top of the stack but must move the whole stack to place one at the bottom.
Adding elements is known as a push, and removing elements is known as a pop. You can implement stacks in Python using the built-in list structure. With list implementation, push operations use the append()
method, and pop operations use pop()
.
Advantages:
Offers LIFO data management that’s impossible with arrays
Automatic scaling and object cleanup
Simple and reliable data storage system
Disadvantages:
Stack memory is limited
Too many objects on the stack leads to a stack overflow error
Applications:
Used for making highly reactive systems
Memory management systems use stacks to handle the most recent requests first
Helpful for questions like parenthesis matching
Implement a queue using stacks
Evaluate a Postfix expression with a stack
Next greatest element using a stack
Create a min()
function using a stack
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
The functions associated with stack are:
empty() – Returns whether the stack is empty – Time Complexity: O(1)
size() – Returns the size of the stack – Time Complexity: O(1)
top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
pop() – Deletes the topmost element of the stack – Time Complexity: O(1)
There are various ways from which a stack can be implemented in Python. This article covers the implementation of a stack using data structures and modules from the Python library. Stack in Python can be implemented using the following ways:
list
Collections.deque
queue.LifoQueue
Python’s built-in data structure list can be used as a stack. Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order. Unfortunately, the list has a few shortcomings. The biggest issue is that it can run into speed issues as it grows. The items in the list are stored next to each other in memory, if the stack grows bigger than the block of memory that currently holds it, then Python needs to do some memory allocations. This can lead to some append() calls taking much longer than other ones.
Python3
Output:
Initial stack ['a', 'b', 'c']
Elements popped from stack: c b a
Stack after elements are popped: []
Traceback (most recent call last): File "/home/2426bc32be6a59881fde0eec91247623.py", line 25, in print(stack.pop()) IndexError: pop from empty list
Python stack can be implemented using the deque class from the collections module. Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity. The same methods on deque as seen in the list are used, append() and pop().
Python3
Output:
Initial stack: deque(['a', 'b', 'c'])
Elements popped from stack: c b a
Stack after elements are popped: deque([])
Traceback (most recent call last): File "/home/97171a8f6fead6988ea96f86e4b01c32.py", line 29, in print(stack.pop()) IndexError: pop from an empty deque
Queue module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using the put() function and get() takes data out from the Queue.
There are various functions available in this module:
maxsize – Number of items allowed in the queue.
empty() – Return True if the queue is empty, False otherwise.
full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() never returns True.
get() – Remove and return an item from the queue. If the queue is empty, wait until an item is available.
get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.
put_nowait(item) – Put an item into the queue without blocking.
qsize() – Return the number of items in the queue. If no free slot is immediately available, raise QueueFull.
Python3
Output:
0 Full: True Size: 3
Elements popped from the stack c b a
Empty: True
The linked list has two methods addHead(item) and removeHead() that run in constant time. These two methods are suitable to implement a stack.
getSize()– Get the number of items in the stack.
isEmpty() – Return True if the stack is empty, False otherwise.
peek() – Return the top item in the stack. If the stack is empty, raise an exception.
push(value) – Push a value into the head of the stack.
pop() – Remove and return a value in the head of the stack. If the stack is empty, raise an exception.
Below is the implementation of the above approach:
Python3
Output:
Stack: 10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1
Pop: 10 Pop: 9 Pop: 8 Pop: 7 Pop: 6
Stack: 5 -> 4 -> 3 -> 2 -> 1
push
in a stack is putting an item on top of the stack.
are a sequential data structure that act as the Last-in, First-out (LIFO) version of queues. The last element inserted in a stack is considered at the top of the stack and is the only accessible element. To access a middle element, you must first remove enough elements to make the desired element the top of the stack.
A great analogy we can use is stacking a pile of books. We always keep a new book on top and remove the topmost book. Stacks are similar to queues in that they are linear collections of items, but they differ in the order in which they are accessed. Stacks are used in a variety of areas from Operating System Software, in Compilers and Language Parsing, and to implement other complex Data Structures like Trees and Graphs.