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

DS e-Content - Module 6 Stack

The document is a module on Stack data structures using Java, detailing concepts such as stack types, operations, and implementations using arrays and linked lists. It covers primitive stack operations like push, pop, and peek, as well as applications of stacks in various computing scenarios. Additionally, it explains the evaluation of postfix and prefix expressions, providing algorithms for their conversion and evaluation.

Uploaded by

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

DS e-Content - Module 6 Stack

The document is a module on Stack data structures using Java, detailing concepts such as stack types, operations, and implementations using arrays and linked lists. It covers primitive stack operations like push, pop, and peek, as well as applications of stacks in various computing scenarios. Additionally, it explains the evaluation of postfix and prefix expressions, providing algorithms for their conversion and evaluation.

Uploaded by

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

School of Computer Science and Engineering

Data Structures using JAVA [R1UC303B]

Module-VI: Stack
Dr. A K Yadav

School of Computer Science and Engineering


Plat No 2, Sector 17A, Yamuna Expressway
Greater Noida, Uttar Pradesh - 203201

November 24, 2024

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 1/27


School of Computer Science and Engineering

Contents

Stack 3
Introduction to Stack 3
Abstract Data Type 6
Primitive Stack operations 9
Stack Implementation 10
Array Implementation of Stack 11
Linked List Implementation of Stack 16
Application of Stack 29
Postfix Expressions 32
Prefix Expressions 34
Evaluation of postfix expression 36

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 2/27


School of Computer Science and Engineering

Introduction to Stack
I A Stack is a linear data structure that follows a particular
order in which the operations are performed.
I The order may be LIFO(Last In First Out) or FILO(First In
Last Out).
I LIFO implies that the element that is inserted last, comes out
first and FILO implies that the element that is inserted first,
comes out last.
I A variable name Top is used to keep the position of the
topmost element in the stack.
I we can access the elements only on the top of the stack

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 3/27


School of Computer Science and Engineering

Figure: Stack Structure

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 4/27


School of Computer Science and Engineering

Types of Stack based on Size:


I Fixed Size Stack : As the name suggests, a 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.
I 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. This type of stack is
implemented using a linked list, as it allows for easy resizing
of the stack.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 5/27


School of Computer Science and Engineering

Abstract Data Type


I Abstract Data type (ADT) is a type (or class) for objects
whose behaviour is defined by a set of values and a set of
operations.
I The definition of ADT only mentions what operations are to
be performed but not how these operations will be
implemented.
I It does not specify how data will be organized in memory and
what algorithms will be used for implementing the operations.
I It is called “abstract” because it gives an
implementation-independent view.
I The process of providing only the essentials and hiding the
details is known as abstraction.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 6/27


School of Computer Science and Engineering

I In Stack ADT implementation instead of data being stored in


each node, the pointer/reference to data is stored.
I The program allocates memory for the data and address is
passed to the stack ADT.
I The head node and the data nodes are encapsulated in the
ADT.
I The calling function can only see the pointer to the stack.
I The stack head structure also contains a pointer to top.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 7/27


School of Computer Science and Engineering

Figure: Stack ADT

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 8/27


School of Computer Science and Engineering

Primitive Stack operations


I Push: Adds an element to the top of the stack
I Pop: Removes the top element from the stack
I Peek: Returns the top element without removing it
I IsEmpty: Checks if the stack is empty
I IsFull: Checks if the stack is full (in case of fixed-size arrays)

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 9/27


School of Computer Science and Engineering

Stack Implementation
I There are two types of Stack based on Size: Fixed Size Stack
and Dynamic Size Stack
I Arrays are used to implement the fixed size Stack.
I Size of the array declared at the time of declaration of the
array in Java is the size of the Stack.
I For example int Stack[20], here maximum stack size is limited
upto 20. and the valid range of the Top is from 0 to 19.
I Top having value -1 is the condition for empty stack and Top
having value 20 is the condition for full stack.
I When stack is empty, nothing can be popped.
I When stack is full, nothing can be pushed.
I Dynamic size stack can be implemented using the link link.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 10/27


School of Computer Science and Engineering

Array Implementation of Stack


I In push, we check the overflow condition. If Top=size-1 then
stack is full and insertion of item is not possible, the stack is
in overflow state.
I In pop, we check the underflow condition. If Top=-1 then
stack is empty and deletion is not possible, the stack is in
underflow state.
I Below is the complete program of stack implementation using
array.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 11/27


School of Computer Science and Engineering
class Stack {
static final int MAX = 2;
int top;
int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()
{
if(top<0) return true; else return false;
//return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int x)
{
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 11/27
School of Computer Science and Engineering
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
top=top+1;
a[top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}

int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 11/27
School of Computer Science and Engineering
}
else {
int x = a[top];
top=top-1;
return x;
}
}

int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 11/27
School of Computer Science and Engineering
}
}
boolean isFull() {
if(top==MAX-1) return true; else false;
}

class StackArray {
public static void main(String args[])
{
Stack s = new Stack();
s.pop();//Stack underflow
s.push(10);
s.push(20);
s.push(30); //Stack overflow
System.out.println(s.pop() + " Popped from stack");
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 11/27
School of Computer Science and Engineering
System.out.println("Top element is :" + s.peek());
}
}

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 12/27


School of Computer Science and Engineering

Linked List Implementation of Stack


I To implement a stack using the singly linked list concept, all
the singly linked list operations should be performed based on
Stack operations LIFO(last in first out) and with the help of
that knowledge, we are going to implement a stack using a
singly linked list.
I In singly linked list if we perform only addition and deletion at
front i.e. at Head and if we rename Head as Top then singly
linked list will be behave just like a Stack.
I In the stack Implementation, a stack contains a top pointer
which is the “head” of the stack where pushing and popping
items happens at the head of the list.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 12/27


School of Computer Science and Engineering

I The first node(right most/bottom most) has a null in the link


field and second node-link has the first node address in the
link field and so on and the last node(left most/top most)
address is in the “top” pointer.

Figure: Stack using SLL

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 13/27


School of Computer Science and Engineering

I The main advantage of using a linked list over arrays is that it


is possible to implement a stack that can shrink or grow as
much as needed.
I Using an array will put a restriction on the maximum capacity
of the array which can lead to stack overflow.
I Here each new node will be dynamically allocated, so overflow
is not possible.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 14/27


School of Computer Science and Engineering

Stack Operations using SLL


I push(): Insert a new element into the stack i.e just insert a
new element at the beginning of the linked list.

Figure: push()

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 15/27


School of Computer Science and Engineering

I pop(): Return the top element of the Stack i.e simply delete
the first element from the linked list.

Figure: pop()

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 16/27


School of Computer Science and Engineering

I peek(): Return the top element.

Figure: peek()

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 17/27


School of Computer Science and Engineering

I isFull(): if newly created node is null then Stack is full.

Figure: isFull()

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 18/27


School of Computer Science and Engineering

I isEmpty(): if top is null then Stack is empty.

Figure: isEmpty()

I Below is the complete program of stack implementation using


singly linked list.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 19/27


School of Computer Science and Engineering
class Node {
int data;
Node next;
Node(){
data = 0;
next = null;
}
Node(int d) {
data = d;
next = null;
}

class StackL {
Node top;
StackL() { //constructor
top = null;
}
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 19/27
School of Computer Science and Engineering

boolean isEmpty() {
if(top==null) return true;
else return false;
}

boolean isFull() {
Node new_node = new Node();
if(new_node==null) return true;
else return false;
}

void push(int new_data) {


Node new_node = new Node(new_data);
if (new_node == null) {
System.out.println("\nStack Overflow");
return;
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 19/27
School of Computer Science and Engineering
}
new_node.next = top;
top = new_node;
}

void pop() {
if (top==null) {
System.out.println("\nStack Underflow");
return;
}
else {
Node temp = top;
top = top.next;
System.out.println("Popped element is " + temp.data);
temp = null;
}
}
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 19/27
School of Computer Science and Engineering

int peek() {
if (top!=null)
return top.data;
else {
System.out.println("\nStack is empty");
return Integer.MIN_VALUE;
}
}
}

public class StackLink {


public static void main(String[] args)
{
// Creating a stack
StackL st = new StackL();
st.pop();
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 19/27
School of Computer Science and Engineering
st.push(11);
st.push(22);
st.push(33);
st.push(44);
System.out.println("Top element is " + st.peek());
System.out.println("Removing two elements...");
st.pop();
st.pop();
System.out.println("Top element is " + st.peek());
}
}

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 20/27


School of Computer Science and Engineering

Application of Stack
I Expression evaluation and conversion: Stacks can evaluate
expressions with operators and operands, and convert
expressions from one form to another
I Backtracking: Stacks can check for matching parentheses in
an expression
I Function call management: Stacks manage function calls in
real-time applications
I Memory allocation: Stacks are used for systematic memory
management
I Task scheduling: Stacks are used for task scheduling in
real-time applications
I Program flow management: Stacks are crucial for
managing program flow
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 20/27
School of Computer Science and Engineering

I History maintenance: Stacks are used to maintain history


I Undo functionality: Stacks are used to implement undo
functionality
I Web browsing history: Stacks help manage web browsing
history in browsers
I System memory architecture: Stacks are used in system
memory architecture
I Postfix Expressions
I Prefix Expressions
I Evaluation of postfix expression

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 21/27


School of Computer Science and Engineering

Postfix Expressions
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, put it in the postfix
expression.
3. Otherwise, do the following
- If the precedence of the current scanned operator is higher
than the precedence of the operator on top of the stack, or if
the stack is empty, or if the stack contains a ‘(‘, then push the
current operator onto the stack.
- Else, pop all operators from the stack that have precedence
higher than or equal to that of the current operator. After that
push the current operator onto the stack.
4. If the scanned character is a ‘(‘, push it to the stack.
5. If the scanned character is a ‘)’, pop the stack and output it
until a ‘(‘ is encountered, and discard both the parenthesis.
Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 22/27
School of Computer Science and Engineering

6. Repeat steps 2-5 until the infix expression is scanned.


7. Once the scanning is over, Pop the stack and add the
operators in the postfix expression until it is not empty.
8. Finally, print the postfix expression.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 23/27


School of Computer Science and Engineering

Prefix Expressions
I Step 1: Reverse the infix expression. Note while reversing
each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
I Step 2: Convert the reversed infix expression to “nearly”
postfix expression. While converting to postfix expression,
instead of using pop operation to pop operators with greater
than or equal precedence, here we will only pop the operators
from stack that have greater precedence.
I Step 3: Reverse the postfix expression.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 24/27


School of Computer Science and Engineering

Figure: Convert infix expression to prefix expression

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 25/27


School of Computer Science and Engineering

Evaluation of postfix expression


I Create a stack to store operands (or values).
I Scan the given expression from left to right and do the
following for every scanned element.
I If the element is a number, push it into the stack.
I If the element is an operator, pop operands for the operator
from the stack. Evaluate the operator and push the result back
to the stack.
I When the expression is ended, the number in the stack is the
final answer.

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 26/27


School of Computer Science and Engineering

Thank you
Please send your feedback or any queries to
[email protected]

Module-VI: Stack Dr. A K Yadav Data Structures using JAVA 27/27

You might also like