Stack Notes
Stack Notes
What is Stack?
Unlike linked list and Array, stack itself is not an independent data structure. Which means it
requires some data structure to implement itself. So, I am going to use:
1. Array:
As static data structure implementation of stack, it will help you write a data structure
that is more robust and concise for fixed data structure stack target. Where size is fixed.
Note: We are not talking about dynamic array or array list here.
2. Linked list:
As dynamic data structure implementation of stack, it will help write a dynamic structure
where size is not fixed and can be extended as per needs of program.
Stack simply means items stored in such a way that the last item stored is first to leave. This
principal professionally is called LIFO meaning Last in first out.
“The first on top of stack of plates is the one that is picked first also the last one that is placed on
stack”
- Ali Mobin the great
1. In stack you cannot reach any item except 1 item that is on top of stack.
Page | 1
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
Operations:
Just like any data structure, stack follows certain rules to operate on. Stack follows following
operations:
1. Push:
Push an item means to insert an item in stack
2. Pop:
Pop an item means to remove an item from stack
3. Peek:
Peek means to get the last item inserted in array and return it.
4. Is Empty:
check if stack is empty
In stack when doing these operations, we use Top as a pointer to decide where you are pointing
in stack right now or are you even inside stack? Without Top, operations like Push, Pop, Peek and
Is Empty check is impossible. The reason is simple as discussed earlier, in stack you cannot
perform any operation in between array. You only do it via Top as discussed in Rules section
above.
Applications in DSA:
Page | 2
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
Infix notation is a notation in which operators appear between the required operands.
Postfix notation is the type of notation in which the operator appears after the operand.
Prefix is a type of notation in which the operator appears before the operand. Stack allows
you to transition from infix to postfix.
To transform an infix expression to a postfix expression, utilise the stack data structure.
Scan the infix expression left to right. When we obtain an operand, add it to the postfix
expression, and if we get an operator or parenthesis, add it to the stack while keeping their
precedence.
Page | 3
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
0 1 1 2 3 5 8 13
Fibonacci series
Here, in Fibonacci series. Each sum is done via recursive function and each recursive
function uses stack to get previous value and not restart whole process for each call of
function.
Note: This list does not mean its best in these applications
Types of stacks:
• fixed size stack has a fixed size and cannot grow or shrink dynamically.
• If the stack is full and an attempt is made to add an element to it, an overflow error
occurs.
• If the stack is empty and an attempt is made to remove an element from it, an
underflow error occurs.
• When the stack is full, it automatically increases its size to accommodate the new
element, and when the stack is empty, it decreases its size.
• It is implemented by incrementing the index of the top element and storing the
new element at that index.
Page | 4
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
• It is implemented by returning the value stored at the top index and then
decrementing the index of the top element.
Fig 5-6: Stack via Array: Array is of size 6. So don’t be confused with 6 to 9 indexes as its just
memory space.
So, here in figure 5 to 6 basically stack via array has same example as figure 2. In array we only
shift top element if performing push and pop operation. Push means go above in array then add
item. Pop means remove item and go back and make previous item a top item.
Page | 5
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
Implementation in Java
Pop and push operation is explained here. Notice how only Top pointer is used for insertion and
deletion (Push and Pop). Comments in code are description on how code is working please read
the comments.
class Stack {
static final int MAX = 1000;
int top;
// Maximum size of Stack
int a[] = new int[MAX];
Stack()
{
top = -1;
}
boolean isEmpty()
{
return (top < 0);
}
int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top]; //save in temp variable x for returning later what item is deleted
a[top] = null; // remove element and reset value to null at top
top--; // decrement of top as top element is removed
return x;
}
}
Page | 6
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
boolean push(int x)
{
// check if top of stack pointer is not already at maximum size of array as it
Will overflow stack
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
top ++; // incrementing top to add new item. First, we move to next index
then add item that’s why.
a[top] = x; // add item to new top index
System.out.println(x + " pushed into stack");
return true;
}
}
void print(){
for(int i = top;i>-1;i--)
{
System.out.print(" "+ a[i]);
}
}
Page | 7
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
System.out.println("Top element is :" + s.peek());
System.out.print("Elements present in stack :");
s.print();
}
}
• Memory is saved as pointers are not involved the bytes stored for pointers are non-
existing
• It is not dynamic. It doesn’t grow and shrink depending on needs at runtime. But in
the case of dynamic sized arrays like vector in C++, list in Python, Array List in Java,
stacks can grow and shrink with array implementation as well.
Page | 8
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
As can be seen in fig 7, In Linked list there is no Top pointer as seen in stack via array. Here, we
can do from beginning of linked list or end of linked list. Its the place where we push or pop a
node.
Page | 9
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
Fig 10: New node added at end of linked list which is top of the stack
Remember we are considering end of linked list by checking last node which can be considered
as Top of stack. In another scenario we can consider first node as Top of stack. Meaning, first
node will be pushed or popped.
Now if we want to pop a node from fig 10, we can do the same by taking top node out of stack as
shown in fig 11 below.
Page | 10
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
Fig 11: Node being popped out of stack via linked list
You simply popped an item out of stack just like you pushed an item and updated pointers of
previous last node. As shown in fig 11.
Page | 11
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
Implementation in Java
if (root == null) {
root = newNode;
}
else {
// New Node is added by swapping pointers with current first node which is top
Node. New node is now first node pointed by root and new node next is pointed
To old first node
Page | 12
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
if (root == null) {
// do nothing as linked list is empty
}
else {
// top Node is removed from root by swapping pointers with current first node
which is top Node. 2nd node is now first node pointed by root as first node is now
popped out to old first node
}
System.out.println(data + " pushed to stack");
}
Page | 13
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University
Main Class
sll.push(10);
sll.push(20);
sll.push(30);
sll.push(10);
sll.push(20);
sll.push(30);
In above code a linked list class via stack is created first inside that members are created. If we
observe its just like basic linked list. We just made 1 restriction that do deletion, insertion via firs
node only if we are setting push and pop from beginning. Or last node in case of end of linked list.
• The linked list implementation of a stack can grow and shrink according to the needs
at runtime.
• It is used in many virtual machines like JVM Java virtual machines. The stack is a linear
data structure that is used to store the collection of objects. It is based on Last-In-
First-Out (LIFO). Java collection framework provides many interfaces and classes to
store the collection of objects.
Page | 14