Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Stack Notes

The document provides an overview of the stack data structure, explaining its definition, operations (push, pop, peek, is empty), and types (fixed size and dynamic size). It discusses implementations using arrays and linked lists, detailing their advantages and disadvantages, as well as applications in expression evaluation, backtracking, undo mechanisms, and function call management. Java code examples illustrate how to implement stack operations using both array and linked list approaches.

Uploaded by

sarimayubi1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Stack Notes

The document provides an overview of the stack data structure, explaining its definition, operations (push, pop, peek, is empty), and types (fixed size and dynamic size). It discusses implementations using arrays and linked lists, detailing their advantages and disadvantages, as well as applications in expression evaluation, backtracking, undo mechanisms, and function call management. Java code examples illustrate how to implement stack operations using both array and linked list approaches.

Uploaded by

sarimayubi1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Sorting something that you will never search is a complete waste,

Searching something you never sorted is merely inefficient


SZABIST University

Data Structures & Algorithm

Ali Mobin Memon

What is Stack?

Stack is a data structure. A data structure that can be continuous/non-continuous, dynamic


sized or static sized and index/non-indexed data structure.

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

Fig 1: Stack of Plates


Rules:

1. In stack you cannot reach any item except 1 item that is on top of stack.

2. You cannot insert any item except after top of stack

3. You cannot delete any item except on top of stack

4. You cannot view any item except top item

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.

Fig 2: Stack Operations

Applications in DSA:

1. Expression evaluation (e.g., postfix, prefix expressions).

Fig 3: Infix to Postfix

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.

If you are interested in this problem, click Here to study (optional)

2. Backtracking algorithms depth-first search (DFS).

Backtracking is another application of Stack. It is a method of solving problems by trying


out different solutions and undoing them by going back and start again if they don't lead
to a valid solution. Backtracking is one of the algorithm design techniques.

Fig 4: DFS Backtracking

3. Undo mechanisms text editors.


Let’s say you are typing, “Artists are good” the last word you typed is “good”. but you
wanted to right “Artists are bad”. So, you undo it by pressing CTRL+Z. Operating system
undo’s the good word by removing it from stack as it’s the last word you typed, and stack
is LIFO.

Page | 3
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University

4. Function call management


Here recursion (function calls are handled using a call stack).
The Fibonacci series is a series where the sum of previous 2 leads to new number.

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.

Otherwise, it would be 0 1 1 1 1 1 1 a repetitive process

Note: This list does not mean its best in these applications

Types of stacks:

Fixed Size Stack:

• 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.

• For example, using Array

Dynamic Size Stack:

• A dynamic size stack can grow or shrink dynamically.

• 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.

• For example, using Linked List

Stack via Array

1. The push operation

• It is implemented by incrementing the index of the top element and storing the
new element at that index.

• In Array overflow issue!

Page | 4
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University

2. The pop operation

• It is implemented by returning the value stored at the top index and then
decrementing the index of the top element.

• Underflow issue can occur

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;
}
}

Code Continued in next page

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;
}
}

Peek function to return value on Top pointer of Stack via array


int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top]; // return value at top
return x;
}
}

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();
}
}

Stack via Array benefits and disadvantage:

• Advantages of Array Implementation:

• Memory is saved as pointers are not involved the bytes stored for pointers are non-
existing

• Disadvantages of Array Implementation:

• 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.

• The total size of the stack must be defined beforehand.

Stack via Linked List

1. The push operation


It is implemented by creating a new node with the new element and setting the next
pointer of the current top node to the new node. Since linked list is dynamic it cannot have
overflow issue.

2. The pop operation


It is implemented by setting the next pointer of the current top node to the next node and
returning the value of the current top node. Since linked list is dynamic it cannot have
overflow issue.

Page | 8
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University

Fig 7: Stack via Linked List

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.

Fig 8: Stack via linked list

Page | 9
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University

Fig 9: New Node being pushed from end of linked list

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.

Fig 12: Stack via linked list

Implementation in next page

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

public class StackNode {


// root node is Top node
StackNode root;
int data;
StackNode next;
StackNode(int data) { this.data = data; }

public boolean isEmpty()


{
if (root == null) {
return true;
}
else
return false;
}

public void push(int data)


{
StackNode newNode = new StackNode(data);

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

StackNode temp = root;


root = newNode;
newNode.next = temp;

System.out.println(data + " pushed to stack");

Page | 12
Sorting something that you will never search is a complete waste,
Searching something you never sorted is merely inefficient
SZABIST University

public void pop(int data)


{

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

// root is replaced by its 2nd node next.


root = root.next;

}
System.out.println(data + " pushed to stack");
}

public int peek()


{
if (root == null) {
System.out.println("Stack is empty");
return Integer.MIN_VALUE;
}
else {
// get first top node of stack from linked list and print
return root.data;
}
}

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

public static void main(String[] args)

StackAsLinkedList sll = new StackAsLinkedList();

sll.push(10);

sll.push(20);

sll.push(30);

System.out.println(sll.pop() + " popped from stack");

System.out.println("Top element is " + sll.peek());

sll.push(10);

sll.push(20);

sll.push(30);

System.out.println(sll.pop() + " popped from stack");

System.out.println("Top element is " + sll.peek());

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.

1. Advantages of Linked List implementation:

• 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.

2. Disadvantages of Linked List implementation:

• Requires extra memory due to the involvement of pointers.

• Random accessing is not possible in stack. Since stack requires to be manipulated


via a pointer Top or head node in case of linked list. It cannot access any other
element other than first or last of node (beginning of linked list or end of linked list)

Page | 14

You might also like