A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This means the last element inserted inside the stack is removed first.
You can think of the stack data structure as the pile of plates on top of another.
Stack representation similar to a pile of plate
Here, you can:
And, if you want the plate at the bottom, you must first remove all the plates on top. This is exactly how the stack data structure works.
In programming terms, putting an item on top of the stack is called push and removing an item is called pop.
Stack Push and Pop Operations
In the above image, although item 3 was kept last, it was removed first. This is exactly how the LIFO (Last In First Out) Principle works.
We can implement a stack in any programming language like C, C++, Java, Python or C#, but the specification is pretty much the same.
There are some basic operations that allow us to perform different actions on a stack.
The operations work as follows:
TOP == -1
.Working of Stack Data Structure
The most common stack implementation is using arrays, but it can also be implemented using lists.
Python
Java
C
C++
# Stack implementation in python
# Creating a stack
def create_stack():
stack = []
return stack
# Creating an empty stack
def check_empty(stack):
return len(stack) == 0
# Adding items into the stack
def push(stack, item):
stack.append(item)
print("pushed item: " + item)
# Removing an element from the stack
def pop(stack):
if (check_empty(stack)):
return "stack is empty"
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
For the array-based implementation of a stack, the push and pop operations take constant time, i.e. O(1)
.
Although stack is a simple data structure to implement, it is very powerful. The most common uses of a stack are:
2 + 4 / 5 * (7 - 9)
by converting the expression to prefix or postfix form.#csharp #c#