0% found this document useful (0 votes)
3 views

Lecture 4 Stack DSA

The document provides an overview of stacks, a linear data structure that operates on a Last In First Out (LIFO) principle, detailing its operations such as push, pop, and peek. It discusses two types of stack implementations: fixed size using arrays and dynamic size using linked lists, along with their advantages and disadvantages. Additionally, it includes Java code examples for stack operations and mentions applications of stacks in data structures and algorithms.

Uploaded by

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

Lecture 4 Stack DSA

The document provides an overview of stacks, a linear data structure that operates on a Last In First Out (LIFO) principle, detailing its operations such as push, pop, and peek. It discusses two types of stack implementations: fixed size using arrays and dynamic size using linked lists, along with their advantages and disadvantages. Additionally, it includes Java code examples for stack operations and mentions applications of stacks in data structures and algorithms.

Uploaded by

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

DATA STRUCTURES

AND ALGORITHMS
STACK

Ali Mobin Memon


What is Stack?

• Its Linear / non-linear data structure. But it cannot be both at the


same time

• Its Static and Dynamic. But it cannot be both at the same time

• Its continuous as well as non-continuous stream of data. But it


cannot be both at the same time

• Depends on way it is executed

• Via linked list

• Via Array
What is Stack - Continued
• It follows LIFO ( 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

• It features two operations

• Push
Means to insert a new item

• Pop
Means to delete an item
Stack Operations
• Key Operations:

• Push: Add an element to the top of the stack.

• Pop: Remove the element from the top of the stack.

• Peek or Top: Look at the top element of the stack


without removing it.

• is Empty: Check if the stack is empty.


Stack Operations
• Applications in DSA:

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

• Backtracking algorithms depth-first search (DFS).

• Undo mechanisms text editors.

• Function call management recursion (function calls are


handled using a call stack).

Note: This list does not mean its best in these applications
import java.util.Stack;

public class StackExample {


public static void main(String[] args) {
// Creating a stack of integers
Stack<Integer> stack = new Stack<>();
// Pushing elements onto the stack
stack.push(10); // Stack: [10]
stack.push(20); // Stack: [10, 20]
stack.push(30); // Stack: [10, 20, 30]

// Displaying the top element


System.out.println("Top element: " + stack.peek()); // Outputs 30

// Popping the top element


stack.pop(); // Stack: [10, 20]

// Displaying the top element after popping


System.out.println("Top element after pop: " + stack.peek()); // Outputs
20
// Checking if the stack is empty
System.out.println("Is stack empty? " + stack.isEmpty()); // Outputs false
}
}
Types of Stack
• 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-Array

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

• 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


Stack-Array
Stack - Array
int pop()
Stack-Array {
if (top < 0) {
Import java.util.Stack; System.out.println("Stack Underflow");
return 0;
}
class Stack { else {
static final int MAX = 1000; int x = a[top--];
a[top--] = null;
int top; return x;
int a[] = new int[MAX]; }
}
// Maximum size of Stack
boolean push(int x)
Stack()
{
{
if (top >= (MAX - 1)) {
top = -1;
System.out.println("Stack Overflow");
}
return false;
}
boolean isEmpty()
{ else {
return (top < 0); a[++top] = x;
}
System.out.println(x + " pushed into stack");
return true;
Stack-Array

int peek() class Main {


{ public static void main(String args[])
if (top < 0) {
System.out.println("Stack Underflow"); {
return 0; Stack s = new Stack();
}
s.push(10);
else {
int x = a[top]; s.push(20);
return x; s.push(30);
}
} System.out.println(s.pop() + " Popped
from stack");
void print(){ System.out.println("Top element is :" +
for(int i = top;i>-1;i--){ s.peek());
System.out.print(" "+ a[i]);
System.out.print("Elements present in
} stack :");
s.print();
} }
}
Stack-Array Advantages & Disadvantages

• 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 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-Link list

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

• No overflow issue!

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

• No underflow issue!
Stack-Link list
Reference to diagrams in ppt notes tab
Stack-Link list
example
Stack-Link list
Push or Pop at end of linked list
Stack-Link list
Push or Pop at end of linked list
Stack-Link list
Push or Pop at beginning of linked list
Stack-Link list
Push or Pop at beginning of linked list
Stack- Linked List
public class StackAsLinkedList { public void push(int data)
{
StackNode root; StackNode newNode = new StackNode(data);
static class StackNode { if (root == null) {
root = newNode;
int data; }
StackNode next; else {
StackNode temp = root;
StackNode(int data) { this.data = data; } root = newNode;
} newNode.next = temp;
}
System.out.println(data + " pushed to stack");
public boolean isEmpty() }

{ public int peek()


if (root == null) { {
if (root == null) {
return true; System.out.println("Stack is empty");
} return Integer.MIN_VALUE;
}
else else {
return false; return root.data;
}
} }
Stack-Array
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());
}
}
Stack-Link list Advantages & Disadvantages

• 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

• Disadvantages of Linked List implementation:

• Requires extra memory due to the involvement of pointers.

• Random accessing is not possible in stack.


Next Week

• 1 hour test before break

• Data structure

• Array

• linked list

• Stack

• Assignment 1 announcement

• To be decided that day

• Deadline: 2 weeks after announcement


Reference

• Geek for Geeks

• CHAT-GPT

• Prep insta
THANK YOU

You might also like