You are on page 1of 152

EL

P T
Data Structures and Algorithms Using Java
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 06: Stack


Lecture 21 : Stack Data Structures
Ø Introduction to Stack

EL
T
Ø Representation of Stacks

P
Ø Array representation

N
Ø Linked list representation Ø Applications of Stack
Ø Operations on Stack Ø Arithmetic expression evaluation
Ø push(), pop() Ø Recursion implementation
Ø Status: isEmpty(); size(), peep() Ø Factorial calculation
EL
T
Introduction to Stack

N P
The concept

L
CARGO

T E
Goods in a cargo

P
out
in

N
Trains in a Railyard Plates on a tray
Definition of stack

• A stack is an ordered collection of homogeneous data element where

L
the insertion and deletion operations take place at one end only.

PUSH
POP

T E
ITEM 1
ITEM 2
ITEM 3
ITEM 4

.
.
.
.
N P
TOP

Stack follows LIFO (Last In First Out) property


Bottom
EL
T
Representations of Stack

P
N
Memory representations

L
Array representation Linked list representation

E
Index 1D Array
STACK_HEAD

T
l Bottom
ITEM1

P
l+1 ITEM2
ITEMi .. . ... ....
l+2 .

N
. .
. . TOP

l+i-1 ITEMi TOP ITEM2

. .
. .
. .

u ITEM1
SIZE = u+l-1
EL
T
Operations on Stack

P
N
Operations on stack

L
Push To insert an item into the stack

E
Pop To remove an item from a stack

Status

P T
To know the present state of a stack
o if stack is empty,

N
o size of the stack,
o the element at top
EL
T
Stack with Array Representation

P
N
Operation: Push with array
We have assumed that the array index varies from 1 to SIZE and TOP points the location of the
current top-most item in the stack. The following algorithm defines the insertion of an item into a

L
stack represented using an array A.
1

E
2

Input: The new item ITEM to be pushed onto it. 3


Push operation is failed
Output: A stack with a newly pushed ITEM at the TOP position.

T
Data structure: An array A with TOP as the pointer.
N-1

P
N TOP

Steps:

N
1. If TOP ≥ SIZE then 1 1

2. Print “Stack is full” 2


3
2
3
3. Else i TOP i
4. TOP = TOP + 1 i+1 TOP

5. A[TOP] = ITEM
6. EndIf N-1

N
N-1

N
7. Stop
Before push() After push()
Operation: Pop with array
The following algorithm defines the deletion of an item from a stack represented using an array A.

L
TOP
1
Input: A stack with elements. 2

E
Output: Removes an ITEM from the top of the stack if it is not empty. 3

Data structure: An array A with TOP as the pointer. i Pop operation is failed
i+1

T
Steps: N-1

P
N
1. If TOP < 1 then
2. Print “Stack is empty”

N
3. Else 1

2
1

2
4. ITEM = A[TOP] 3 3

5. TOP = TOP – 1 i-1 i-1 TOP

6. EndIf i TOP i

7. Stop N-1 N-1

N N

Before Pop() After Pop()


Operation: Status with array

The following algorithm tests the various states of a stack such as whether it is full or empty, how
many items are right now in it, and read the current element at the top without removing it, etc.

Steps:
1. If TOP < 1 then

EL
T
2. Print “Stack is empty”

P
3. Else
4. If (TOP ≥ SIZE) then

N
5. Print “Stack is full”
6. Else
7. Print “The element at TOP is”, A[TOP]
8. free = (SIZE – TOP)/SIZE * 100
9. Print “Percentage of free stack is”, free
10. EndIf
11. EndIf
12. Stop
EL
T
Stack with Linked List

P
N
Operation: Push with linked list
Input: ITEM is the item to be inserted.
Output: A single linked list with a newly inserted node with data content ITEM.

L
Data structure: A single linked list structure whose pointer to the header is known from STACK_H and TOP is the pointer to the first
node.

E
TOP

T
Header

Steps:

P
Before push()
1. new = GetNode(NODE)
/* Insert at front */

N
2. new®DATA = ITEM Header

3. new®LINK = TOP
4. TOP = new TOP

5. STACK_H®LINK = TOP
6. Stop
After push()
Operation: Pop with linked list
Input: A stack with elements.
Output: The removed item is stored in ITEM.

L
Data structure: A single linked list structure whose pointer to the header is known from STACK_H and TOP is the pointer to the first
node.

E
TOP

Header

T
Steps: Before Pop()

P
1. If TOP = NULL

rn
2. Print “Stack is empty”

tu
Re
TOP

N
3. Exit Header

4. Else
5. ptr = TOP®LINK
6. ITEM = TOP®DATA After Pop()
7. STACK_H®LINK = ptr
8. TOP = ptr TOP

9. EndIf Header

10. Stop NULL Failed Pop()


Operation: Status with linked list
Input: A stack with elements.
Output: Status information such as its state (empty or full), number of items, item at the TOP.
Data structure: A single linked list structure whose pointer to the header is known from STACK_H and TOP is the pointer to the

L
first node.

E
Steps:
1. ptr = STACK_H®LINK

T
2. If (ptr = NULL) then
3. Print “Stack is empty”

P
4. Else
5. nodeCount = 0

N
6. While (ptr ¹ NULL) do
7. nodeCount = nodeCount + 1
8. ptr = ptr®LINK
9. EndWhile
10. Print “Top item:”, TOP®DATA,
“Size = ”, nodeCount
11. EndIf
12. Stop
EL
T
Applications of Stack

P
N
Some common applications

• Stack is extensively used in system programming

L
3. Scope rule implementation

E
1. Evaluation of arithmetic expression • Static and dynamic scope rule management
• Conversion an expression to postfix notation • Activation record management
Evaluation for the value

T

• Machine code generation 4. Memory management

P
• Run-time memory management
2. Execution of recursive call of a function • Code generation

N
• Factorial calculation • Syntax parsing
• Tower of Hanoi
• Quick sort
• Merge sort
Some common applications

L
3. Scope rule implementation

E
1. Evaluation of arithmetic expression • Static and dynamic scope rule management
• Conversion an expression to postfix notation • Activation record management
Evaluation for the value

T

• Machine code generation 4. Memory management

P
• Run-time memory management
2. Execution of recursive call of a function • Code generation

N
• Factorial calculation • Syntax parsing
• Tower of Hanoi
• Quick sort
• Merge sort
EL
T
Arithmetic Expression Evaluation

N P
Application: An arithmetic expression

A+B*C/D–E^F*G

EL
T
Precedence and associativity of operators
Operators Precedence Associativity

P
– (unary), +(unary), NOT 6 –

N
^ (exponentiation) 6 Right to left
* (multiplication), / (division) 5 Left to right
+ (addition), – (subtraction) 4 Left to right
<, <=, +, < >, >= 3 Left to right
AND 2 Left to right
OR, XOR 1 Left to right
Application: An arithmetic expression evaluation
Precedence and associativity of operators
Operators Precedence Associativity

A+B*C/D–E^F*G
– (unary), +(unary), NOT 6 –

L
^ (exponentiation) 6 Right to left
* (multiplication), / (division) 5 Left to right

E
+ (addition), – (subtraction) 4 Left to right
<, <=, +, < >, >= 3 Left to right
AND 2 Left to right
OR, XOR 1 Left to right

P T
N
Application: An arithmetic expression in parenthesized form
Precedence and associativity of operators
Operators Precedence Associativity

A+B*C/D–E^F*G
– (unary), +(unary), NOT 6 –

L
^ (exponentiation) 6 Right to left
* (multiplication), / (division) 5 Left to right

E
+ (addition), – (subtraction) 4 Left to right
<, <=, +, < >, >= 3 Left to right
AND 2 Left to right
OR, XOR 1 Left to right

P T
N
Application: An arithmetic expression in FORCED parenthesized form

L
((A + B) * ((C/D) – (E ^ (F * G))))

T E
N P
Application: Postfix notation of an arithmetic expression

A+B*C/D–E^F*G

EL
P T
N
Application: Postfix notation of an arithmetic expression

((A + ((B ^ C) – D)) * (E – (A/C)))

EL
P T
NABC^D–+EAC/–*
Application: Conversion of an infix expression to postfix expression

In-stack and in-coming priorities of symbols

Symbol

EL
In-stack priority value In-coming priority value

T
+– 2 1

P
*/ 4 3
^ 5 6

N
operand 8 7
( 0 9
) – 0
Application: Conversion of an infix expression to postfix expression

Procedure to perform expression conversion

EL
Function Description
ReadSymbol( ) From a given infix expression, this will read the next symbol.

T
ISP(X) Returns the in-stack priority value for a symbol X.

P
ICP(X) This function returns the in-coming priority value for a symbol X.
Output(X) Append the symbol X into the resultant expression.

N
Application: Conversion of an infix expression to postfix expression
Input: E, simple arithmetic expression in infix notation delimited at the end by the right parenthesis ‘)’, incoming and in-
stack priority values for all possible symbols in an arithmetic expression.
Output: An arithmetic expression in postfix notation.

L
Data structure: Array representation of a stack with TOP as the pointer to the top-most element.

E
Steps:
1. TOP = 0, PUSH(‘(‘) // Initialize the stack

T
2. While (TOP > 0) do
3. item = E.ReadSymbol( ) // Scan the next symbol in infix expression

P
4. x = POP( ) // Get the next item from the stack
5. Case: item = operand // If the symbol is an operand

N
6. PUSH(x) // The stack will remain same
7. Output(item) // Add the symbol into the output expression
8. Case: item = ‘)’, // Scan reaches to its end
9. While x ¹ ‘(’ do // Till the left match is not found
10. Output(x)
11. x = POP( )
12. EndWhile
Application: Conversion of an infix expression to postfix expression

13. Case: ISP(x) ³ ICP(item)


14. While (ISP(x) ³ ICP(item)) do

L
15. Output(x)

E
16. x = POP( )
17. EndWhile

T
Note:18.This isPUSH(x)
a procedure irrespective of the type of memory representation of the stack to convert an infix
expression
19. to itsPUSH
postfix form using the basic operations of the stack, namely PUSH and POP. These operations
(item)

P
20. Case:
can be replaced ISP(x)
with their< ICP(item)
respective versions and hence implementable to stack with any type of memory
21.
representation. PUSH(x)

N
22. PUSH (item)
23. Otherwise:
Print “Invalid expression”
24. EndWhile
25. Stop
Application: Evaluation of a postfix expression
Input: E, an expression in postfix notation, with values of the operands appearing in the expression.
Output: Value of the expression.

L
Data structure: Array representation of a stack with TOP as the pointer to the top-most element.

T E
N P
Application: Evaluation of a postfix expression
Steps:
1. Append a special delimiter ‘#’ at the end of the expression

L
2. item = E.ReadSymbol( ) // Read the first symbol from E
3. While (item ¹ ‘#’) do

E
4. If (item = operand) then
5. PUSH(item) // Operand is the first push into the stack

T
6. Else
7. op = item // The item is an operator

P
8. y = POP( ) // The right-most operand of the current operator
9. x = POP( ) // The left-most operand of the current operator
10. t = x op y // Perform the operation with operator ‘op’ and operands x, y

N
11. PUSH(t) // Push the result into stack
12. EndIf
13. item = E.ReadSymbol( ) // Read the next item from E
14. EndWhile
15. value = POP( ) // Get the value of the expression
16. Return(value)
17. Stop
EL
T
Recursion Implementation

P
N
Application: Recursive function call
N! = 1× 2 × 3 × … ×(N-2) × (N-1) ×N
Input: An integer number N. = N ×(N-1) ×(N-2) ×… ×3 ×2 ×1
Output: The factoral value of N, that is N!.

L
Remark: Code using the recursive definition of factorial. 0! = 1

E
Steps:

T
1. If (N = 0) then // Termination condition of repetition
2. fact = 1

P
3. Else
4. fact = N * Factorial_R(N – 1)
5. EndIf

N
6. Return(fact) // Return the result
7. Stop
Application: Recursive function call
Steps:
1. If (N = 0) then // Termination condition of repetition
2. fact = 1

L
3. Else
4. fact = N * Factorial_R(N – 1)

E
5. EndIf
6. Return(fact) // Return the result

T
7. Stop

5!

P
Steps:

N
1. 5! = 5*4!
2. 4! = 4*3!
3. 3! = 3*2!
4. 2! = 2*1!
5. 1! = 1*0!
6. 0! = 1
7. 1! = 1
8. 2! = 2
9. 3! = 6
10. 4! = 24
11. 5! = 120
EL
P
For more discussion on stack

T
N
applications see the book
Classic Data Structures
Chapter 4
Prentice Hall of India, 2nd Ed.
EL
PT
N
EL
P T
Data Structures and Algorithms Using Java
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 06: Stack


Lecture 22 : Programming for Stack
EL
T
Ø Implementation of stack using array
Ø Defining a stack using array

P
Ø Operations

N
Ø Implementation of stack using linked list
Ø Defining a stack using linked list
Ø Operations

Ø Applications
Ø Infix to postfix conversion
EL
Implementation of Stack Using

P
Array
T
N
Example 22.1: Defining the class stack using array

// This program shows how a stack can be defined using an array

L
/* import arrayPacakge;

E
this program uses array related implementation; so, include the directory,
where all those programs are defined. */

T
class StackA<T> {
T[] data;

P
int length;
int top;

N
StackA(T[] a) {
data = a;
length = a.length;
top = -1;
}

/* The methods push(), pop(), isEmpty(), printStack() are to be defined here.


See the next slides. */
}
Example 22.2: Defining the method push()

L
// This part of the program includes the definition of the push() method

E
// Defining the push operation
void push(T a) {

T
if(top < length-1) {
top++;

P
data[top] = a;
}
else {

N
System.out.println("Stack Overflow");
}
}

// The next method pop() is to be defined here .... See the next slide
Example 22.3: Defining the method pop()

L
// This part of the program includes the definition of the pop() method

E
// Defining the pop operation
T pop() {
T a = null;

T
if(top == -1) {
System.out.println("Stack Underflow ");

P
}
else {

N
a = data[top];
top--;
}
return a;
}

// The next method isEmpty() is to be defined here .... See the next slide
Example 22.4: Defining the method isEmpty()

L
// This part of the program includes the definition of the isEmpty() method

E
// Defining an operation to print an entire stack content

T
boolean isEmpty() {
if(top == -1) {

P
return true;
}
else {

N
return false;
}
}

// The next method printStack()is to be defined here .... See the next slide
Example 22.5: Defining the method printStack()

L
// This part of the program includes the definition of the printStack() method

E
// Defining an operation to print an entire stack content

void printStack() {

T
if(top == -1) {
System.out.println("Stack Empty");

P
}
else {

N
for(int i = top; i>=0 ; i--) {
System.out.print(data[i] + " ");
}
System.out.println();
}
}
} // End of thed efinition of the class StackA
Example 22.6: Basic stack operations using the class StackA
/* This is the main program, illustration the usage of the class defined. You
should include the package, where this program is stored. */

L
class StackAImplementationDemo {

E
public static void main(String[] args) {
Integer a[] = new Integer[2];
StackA<Integer> st = new StackA<Integer>(a);

T
st.push(5);

P
st.printStack();
st.push(6);
st.push(7);

N
st.printStack();
st.pop();
st.printStack();
st.pop();
st.printStack();
st.pop();
System.out.println(“ Is empty? “ + st.isEmpty();
}
} // End of the demo class
EL
T
Implementation of Stack Using

P
Linked List

N
Example 22.7: Defining the class stack using linked list

// This program shows how a stack can be defined using a linked list

L
/* import jLLPacakge;

E
this program uses linked list related implementation; so, include the directory,
where all those programs are defined. */

T
class StackL<T> {
JLinkedList<T> top; // Header to the list

P
int t; // Length of the list
StackL() {

N
top = new JLinkedList<T>();
t=0;
}
/* The methods push(), pop(), isEmpty(), printStack() are to be defined here.
See the next slides. */
}
Example 22.8: Defining the method push()

EL
// This part of the program includes the definition of the push() method

T
// Defining the push operation
void push(T data) {

P
t += 1;
this.top.insertFront(data);

N
}

// The next method pop() is to be defined here .... See the next slide
Example 22.9: Defining the method pop()

L
// This part of the program includes the definition of the pop() method

// Defining the pop operation

E
T pop() {
T data = null;

T
if(!isEmpty()){
t-=1;

P
this.top.deleteFront();
}
else {

N
System.out.print("Stack Underflow");
}
return data;
}
// The next method isEmpty() is to be defined here .... See the next slide
Example 22.10: Defining the method isEmpty()

L
// This part of the program includes the definition of the isEmpty() method

E
// Defining an operation to print an entire stack content
boolean isEmpty(){
if(this.top.isEmpty()) {

T
return true;

P
}
else {
return false;

N
}
}

// The next method printStack()is to be defined here .... See the next slide
Example 22.11: Defining the method printStack()

EL
// This part of the program includes the definition of the printStack() method

// Defining an operation to print an entire stack content

T
void printStack() {
if(this.top.isEmpty()) {

P
System.out.print("Stack is Empty");
}
else {

N
this.top.printList();
}
}
} // End of the definition of the class StackL
Example 22.12: Basic Stack operation using the class StackL

/* This is the main program, illustration the usage of the class defined.

L
You should include the package, where this program is stored. */

class StackLImplementationDemo {

E
public static void main(String[] args) {
StackL<Integer> st = new StackL<Integer>();

T
st.push(5);

P
st.printStack();
st.push(6);
st.push(7);

N
st.printStack();
st.pop();
st.printStack();
st.pop();
st.printStack();
st.pop();
}
} // End of the demo class
EL
T
Applications of Stack

P
N
Example 22.13: Infix to postfix conversion

// This program shows how a stack can be defined using a linked list

L
/* import jLLPacakge;

E
this program uses linked list related implementation; so, include the directory,
where all those programs are defined. */

T
class StackL<T> {
JLinkedList<T> top; // Header to the list

P
int t; // Length of the list
StackL() {

N
top = new JLinkedList<T>();
t=0;
}
/* The methods push(), pop(), isEmpty(), printStack() are to be defined here.
See the next slides. */
}
Example 22.13: Infix to postfix conversion

class InfixToPostfix {
// The method to return precedence of a given operator

L
// Higher returned value means higher precedence

static int Prec(char ch) {

E
switch (ch) {
case '+':

T
case '-':
return 1;

P
case '*':
case '/':
return 2;

N
case '^':
return 3;
}
return -1;
}
Example 22.13: Infix to postfix conversion

// The method that converts given infix expression to postfix expression.

L
static String infixToPostfix(String exp) {
// initializing empty String for result
String result = new String("");

E
// initializing empty stack

T
StackL<Character> stack = new StackL<>();

for (int i = 0; i<exp.length(); ++i) {

P
char c = exp.charAt(i);

// If the scanned character is an operand, add it to output.

N
if (Character.isLetterOrDigit(c))
result += c;

// If the scanned character is an '(', push it to the stack.


else if (c == '(')
stack.push(c);
Example 22.13: Infix to postfix conversion
// If the scanned character is an ')', pop and output from the stack
// until an '(' is encountered.
else if (c == ')') {

L
while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();

E
if (!stack.isEmpty() && stack.peek() != '(')
return "Invalid Expression"; // invalid expression

T
else
stack.pop();

P
}
else { // an operator is encountered
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){

N
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
stack.push(c);
}
}
Example 22.13: Infix to postfix conversion

L
// pop all the operators from the stack
while (!stack.isEmpty()){

E
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();

T
}
return result;

P
}

// Driver method

N
public static void main(String[] args) {
String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(exp));
}
}
Example 22.13: Postfix expression evaluation

public class ExpressionEvaluation {


// Method to evaluate value of a postfix expression

L
static int evaluatePostfix(String exp) {
//create a stack

E
StackL<Integer> stack=new StackL<>();

// Scan all characters one by one

T
for(int i=0;i<exp.length();i++)
{

P
char c=exp.charAt(i);

// If the scanned character is an operand (number here),


// push it to the stack.

N
if(Character.isDigit(c))
stack.push(c - '0');

// If the scanned character is an operator, pop two


// elements from stack apply the operator
else {
int val1 = stack.pop();
int val2 = stack.pop();
Example 22.13: Postfix expression evaluation
switch(c) {
case '+':
stack.push(val2+val1);
break;

L
case '-':
stack.push(val2- val1);

E
break;

case '/':

T
stack.push(val2/val1);
break;

P
case '*':
stack.push(val2*val1);
break;
}

N
}
}
return stack.pop();
}

// Driver program to test above functions


public static void main(String[] args)
{
String exp="231*+9-";
System.out.println("postfix evaluation: "+evaluatePostfix(exp));
}
}
EL
P T
Ø Classic Data Structures, Debasis Samanta, 2nd Edition, Prentice Hall of India

N
Ø https://cse.iitkgp.ac.in/~dsamanta/javads/index.html
EL
PT
N
EL
P T
Data Structures and Algorithms Using Java
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 06: Stack


Lecture 23 : Stack Using JCF
EL
T
Ø About the Class Stack

P
Ø Creating a Stack

N
Ø Initializing a Stack
Ø Copying a Stack
Ø Operations on Stack
EL
T
About Stack Class

P
N
The class Stack

Object

L
AbstractCollection Collection

T E
AbstractList List

P
Vector

N
Stack

• In Java collection framework, the class Vector is a legacy class.


• Stack is a sub class of the class Vector
• It implements a standard last-in, first-out (LIFO) data structure called stack.
Methods defined in the class Stack

Methods Description

L
boolean empty( ) Returns true if the stack is empty, and returns false if the stack contains
elements.

E
E peek( ) Returns the element on the top of the stack, but does not remove it.

T
E pop( ) Returns the element on the top of the stack, removing it in the process.

P
E push(E element) Pushes element onto the stack. element is also returned.
int search(Object Searches for element in the stack. If found, its offset from the top of the

N
element) stack is returned. Otherwise, –1 is returned.

Note:
• The methods which are available for the Vector class is also available to the Stack class, in
addition, it has its own methods.
EL
T
Creating a Stack

P
N
Constructors

EL
• The class Stack has the single default constructor, which is to
create an empty stack.

P T
N
Example 23.1: Creating a stack

L
// This program illustrates how to declare a stack as a collection

E
import java.util.Stack;

T
public class StackCreateDemo {

P
public static void main(String a[]){
// Creating a stack of integers
Stack<Integer> stack = new Stack<Integer>();

N
System.out.println(“Stack contains : " + stack); // Printing the stack
System.out.println(“Is stack empty? : " + stack.empty());
}
}
EL
T
Basic Stack Operations

P
N
Basic methods related to handle a stack

Methods Description

L
boolean empty( ) Returns true if the stack is empty, and returns false if the stack contains

E
elements.
E peek( ) Returns the element on the top of the stack, but does not remove it.

T
E pop( ) Returns the element on the top of the stack, removing it in the process.

P
E push(E element) Pushes element onto the stack. element is also returned.

N
int search(Object Searches for element in the stack. If found, its offset from the top of the stack
element) is returned. Otherwise, –1 is returned.
Example 23.2: A stack with basic operations

L
// This program illustrates some basic operations on a stack

E
import java.util.Stack;

public class StackOperationsDemo {

T
public static void main(String a[]){
// Creating a stack of integers

P
Stack<Integer> stack = new Stack<Integer>();
System.out.println("Empty stack : " + stack);

N
System.out.println("Empty stack : " + stack.empty());

/* Following statement will throw an exception if you pop an


item from an empty stack. */
System.out.println("Empty stack : Pop Operation : " + stack.pop());

// Continued to next…
Example 23.2: A stack with basic operations

// Continued on…

L
// Inserting some data into the stack created
stack.push(1);

E
stack.push(22);
stack.push(333);
stack.push(4444);

T
// Print the entire stack now

P
System.out.println(“Data in the stack : " + stack);
System.out.println("Pop operation : " + stack.pop());

N
System.out.println("After pop Operation : " + stack);
System.out.println("The element at the top : " + stack.peep());
System.out.println("After peep operation : " + stack);
System.out.println("Search operation: " + stack.search(22));
System.out.println("Is stack empty? " + stack.empty());
}
}
EL
T
Loading a Stack

P
N
Example 23.3: Loading a stack with an array of objects

/*This program illustrates how a Stack object can be created with an array of

L
characters.*/

E
import java.util.Stack;
public class ArrayToStackExample1 {
public static void main(String a[]){

T
// The input array of expression a+b*c-5
String[] expArray = { “a”, “+”, “b” , “*”, “c”, “-“, “5”};

P
// Create a Stack object of type String
Stack<String> stack = new Stack<String>();

N
// Loading the array into stack
for(String s : expArray){
stack.push(s);
}
System.out.println("The stack : " + stack);
}
}
Example 23.4: Another example - Array to stack loading

//To create a Stack object with an array of integers

L
import java.util.Stack;

E
public class ArrayToStackExample2 {
public static void main(String a[]){

T
Integer[] intArr = { 1001,1002,1003,1004};
Stack<Integer> stack = new Stack<>();

P
for(Integer i : intArr){
stack.push(i);

N
}
System.out.println(“The stack: " + stack);
stack.push(1001);
stack.search(1001);
System.out.println(“Verify the result: " + stack);
}
}
Example 23.5: ArrayList to stack loading

/*To initialize a stack with a given List of integers stored in a collection object

L
of type ArrayList.*/

E
import java.util.*;
public class ArrayListToStackExample {

T
public static void main(String a[]){
// Create a collection object of type ArrayList

P
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);

N
list.add(3);
Stack<Integer> stack = new Stack<Integer>(); // Declare a Stack object
stack.addAll(list); // Loading the stack with the collection items
// Printing the first item in the stack
System.out.println("Top item in the stack : " + stack.peep());
}
}
EL
T
Copying a Stack

P
N
Example 23.6: Copying a stack to a collection object

/* The following program illustrates the copy of a stack to a collection object of

L
type ArrayList.*/

E
import java.util.*;
public class StackToArrayListCopyDemo {
public static void main(String a[]){

T
Stack<Integer> stack = new Stack<Integer>();// The Input stack
stack.push(1);

P
stack.push(2);
stack.push(3);

N
// Create a collection object of type ArrayList
ArrayList<Integer> list = new ArrayList<Integer>();
list.addAll(stack);// Copy the elements in stack to the collection
System.out.println("Non-Empty stack : " + stack);// Printing the Stack
System.out.println("Non-Empty List : " + list);// Printing the ArrayList
}
}
EL
T
Few More Operations

N P
Example 23.7: Basic operations like push, pop and peek

/*To create a stack and Performing basic operations like push, pop and peek*/

L
import java.util.*;

E
public class StackExample {

T
public static void main(String[] args) {
// Creating a Stack

P
Stack<String>stackOfCards = new Stack<String>();
// Pushing new items to the Stack
stackOfCards.push("Jack");

N
stackOfCards.push("Queen");
stackOfCards.push("King");
stackOfCards.push("Ace");
System.out.println("Stack => " + stackOfCards);
System.out.println();

// Continued to next…
Example 23.7: Basic operations like push, pop and peek

L
// Continued to next…

// Popping items from the Stack

E
String cardAtTop = stackOfCards.pop();
// Throws EmptyStackException if the stack is empty

T
System.out.println("Stack.pop() => " + cardAtTop);
System.out.println("Current Stack => " + stackOfCards);

P
System.out.println();
// Get the item at the top of the stack without removing it
cardAtTop = stackOfCards.peek();

N
System.out.println("Stack.peek() => " + cardAtTop);
System.out.println("Current Stack => " + stackOfCards);
}
}
Example 23.8: Checking empty, size and searching on stack

/* To Check: If the stack is empty | Find the size of the stack. | Search for an

L
element in the Stack.*/

E
import java.util.Stack;

public class StackSizeSearchExample {

T
public static void main(String[] args) {
Stack<String>stackOfCards = new Stack<>();

P
stackOfCards.push("Jack");
stackOfCards.push("Queen");

N
stackOfCards.push("King");
stackOfCards.push("Ace");
System.out.println("Stack : " + stackOfCards);
// Check if the stack is empty
System.out.println("Is Stack empty? : " + stackOfCards.isEmpty());

// Continued to next…
Example 23.8: Checking Empty, Size and Searching in Stack

// Continued to next…

L
// Find the size of Stack

E
System.out.println("Size of Stack : " + stackOfCards.size());
// Search for an element
// The search() method returns the

T
// 1-based position of the element from the top of the stack
// It returns -1 if the element was not found in the stack

P
int position = stackOfCards.search("Queen");
if(position != -1) {

N
System.out.println("Found element \"Queen\" at position : " + position);
} else {
System.out.println("Element not found");
}
}
}
EL
T
Stack traversal

P
N
Example 23.9: Iterating a stack

/* Iterate using: forEach() | iterator() | forEachRemaining() | listIterator() */

L
import java.util.Iterator;
import java.util.ListIterator;

E
import java.util.Stack;

T
public class IterateOverStackExample {
public static void main(String[] args) {

P
Stack<String>stackOfPlates = new Stack<>();
stackOfPlates.add("Plate 1");
stackOfPlates.add("Plate 2");

N
stackOfPlates.add("Plate 3");
stackOfPlates.add("Plate 4");
System.out.println("=== Iterate over Stack using forEach() method ===");
stackOfPlates.forEach(plate -> {
System.out.println(plate);
});
// Continued to next…
Example 23.9: Iterating a stack

L
// Continued on …

E
System.out.println("\n=== Iterate over a Stack using iterator() ===");
Iterator<String>platesIterator = stackOfPlates.iterator();

T
while (platesIterator.hasNext()) {
String plate = platesIterator.next();

P
System.out.println(plate);
}

N
// Continued to next…
Example 23.9: Iterating a stack

// Continued on…

L
System.out.println("\n=== Iterate over a Stack from TOP to BOTTOM using

E
listIterator() ===");
// ListIterator allows you to traverse in both forward and backward directions.
// We'll start from the top of the stack and traverse backwards.

T
ListIterator<String>platesListIterator =

P
stackOfPlates.listIterator(stackOfPlates.size());
while (platesListIterator.hasPrevious()) {

N
String plate = platesListIterator.previous();
System.out.println(plate);
}
}
}
EL
P T
Ø The Complete Reference, Herbert Schildt, 9th Edition, Oracle Press

N
Ø https://cse.iitkgp.ac.in/~dsamanta/javads/index.html

Ø https://docs.oracle.com/javase/tutorial/
EL
PT
N
EL
P T
Data Structures and Algorithms Using Java
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 07: Queue


Lecture 24 : Queue Data Structure
Ø About Queue Data Structures

EL
T
Ø Operations on Queue

P
Ø Enqueue

N
Ø Dequeue
Ø Status
Ø Different Queue Structures
Ø DEQueue
Ø Priority Queue
Ø Applications of Queue
EL
T
About Queue

N P
Concept of queue: Some real-life applications

‚
‚‚
‚‚‚
EL --
--
--

T
--
-- Waiting register

P
--

N
RUNNING

Q2
Q1

AWAITED
READY
Concept of queue data structure

L
Queue is an ordered collection of homogeneous data elements where, insertion and deletion
operations take place at two extreme ends.

T E
P
REAR FRONT

N
ENQUEUE DEQUEUE

Queue follows FIFO (First In First Out) property


EL
T
Memory Representation of

P
Queue

N
Memory representation for queue: Array

Array representation

L
• A one-dimensional array is used and it is a better choice where a queue of fixed size is required.

T E
P
N-2
N-1
1 2 3

N
N FRONT REAR
Memory representation for queue: Linked list

Linked list representation

L
• A double linked list is used which provides a queue whose size can vary during processing.

T E
P
HEADER FRONT REAR

N
DATA1 DATA2 ............. DATAn
EL
T
Operations of Queue

P
N
Operations of queue

L
Enqueue To insert an item into a queue

E
Dequeue To remove an item from a queue

T
Status To know the present state of a queue

N P
EL
T
Operations of Queue using

P
Array

N
Enqueue operation with array representation of queue
Input: An element ITEM that has to be inserted.
Output: The ITEM is at the REAR of the queue.

L
Data structure: Q is the array representation of a queue structure; two pointers FRONT and REAR of the queue Q are known.

E
Steps:
1.If (REAR = N) then // Queue is full

T
2. Print “Queue is full”

P
3. Exit
4.Else

N
5. If (REAR = 0) and (FRONT = 0) then// Queue is empty
6. FRONT = 1
7. EndIf
8. REAR = REAR + 1// Insert the item into the queue at REAR
9. Q[REAR] = ITEM
10. EndIf
11. Stop
Dequeue operation with array representation of queue
Input: A queue with elements. FRONT and REAR are the two pointers of the queue Q.
Output: The deleted element is stored in ITEM.

L
Data structure: Q is the array representation of a queue structure.
Steps:

E
1.If (FRONT = 0) then
2. Print “Queue is empty”

T
3. Exit

P
4.Else
5. ITEM = Q[FRONT] // Get the element

N
6. If (FRONT = REAR) // When the queue contains a single element
7. REAR = 0 // The queue becomes empty
8. FRONT = 0
9. Else
10. FRONT = FRONT + 1
11. EndIf
12. EndIf
13. Stop
Status operation with array representation of queue
Input: An element ITEM that has to be inserted.
Output: The ITEM is at the REAR of the queue.

L
Data structure: Q is the array representation of a queue structure; two pointers FRONT and REAR of the queue Q are known.

E
Steps:
1.If (REAR = N) then // Queue is full

T
2. Print “Queue is full”

P
3. Exit
4.Else

N
5. If (REAR = 0) and (FRONT = 0) then// Queue is empty
6. FRONT = 1
7. EndIf
8. REAR = REAR + 1// Insert the item into the queue at REAR
9. Q[REAR] = ITEM
10. EndIf
11. Stop
EL
T
Operations of Queue Using

P
Linked List

N
Operations with inked list representation of queue
Insert: Insert at the END
HEADER FRONT REAR

L
Delete: Delete at the FRONT

E
DATA1 DATA2 ............. DATAn
Status:
Queue is empty

T
FRONT = REAR = HEADER

P
HEADER→RLINK = NULL

N
Queue contains at least one element
HEADER→RLINK ≠ NULL
EL
T
Variation of Queue Structures

P
N
EL
T
Circular Queue

P
N
Circular queue

....

L
....

n-1 n
1

E
n-2
2
.
. 3 FRONT REAR

T
.
. 4
.

P
.
.
j+1 . .................. ............. ................

N
i-1
j
j-1 i n n-1 j i 1
i+1
(b) Circular array (physical)
FRONT ......
.
REAR

(a) Circular queue (logical)


EL
T
Operations of CQ

P
N
Insertion operation of circular queue
FRON
REAR
Algorithm EnqueueCQ T

L
1. If (FRONT = 0) then // When queue is empty
2. FRONT = 1

E
.................. ............. ................
3. REAR = 1
4. CQ[FRONT] = ITEM n n-1 j i 1
5.

T
Else // Queue is not
empty
6. next = (REAR MOD LENGTH) + 1

P
7. If (next ¹ FRONT) then // If queue is not full
8. REAR = next

N
9. CQ[REAR] = ITEM
10. Else
11. Print “Queue is full”
12. EndIf
13. EndIf
14. Stop
Deletion operation of circular queue
FRON
REAR
Algorithm DequeCQ T

L
1. If (FRONT = 0) then
2. Print “Queue is empty”

E
3. Exit .................. ............. ................

4. Else n n-1 j i 1
5. ITEM = CQ[FRONT]

T
6. If (FRONT = REAR) then // If the queue contains single element
7. FRONT = 0

P
8. REAR = 0
9. Else
10. FRONT = (FRONT MOD LENGTH) + 1

N
11. EndIf
12. EndIf
13. Stop
Status operation of circular queue
Principle:
FRON
• Both pointers will move in clockwise direction. This is controlled by T
REAR

L
the MOD operation; for example, if the current pointer is at i then
shift to the next location will be i MOD LENGTH + 1, 1 ≤ i ≤ LENGTH

E
(where LENGTH is the queue length). Thus, if i = LENGTH (that is at .................. ............. ................
the end), then next position for the pointer is 1. n n-1 j i 1

T
With this principle the two states of the queue regarding its

P
empty or full will be decided as:

N
Circular queue is empty
FRONT = 0
REAR = 0
Circular queue is full
FRONT = (REAR MOD LENGTH) + 1
DEQueue:
EL
P T
Double Ended Queue

N
DEQueue: Double-ended queue
• Another variation of the queue is known as dequeue (pronounced as ‘deck’).
• The term dequeue has originated from double ended queue.

L
• In DEqueue, both insertion and deletion operations can be made at either end of the structure.

FRONT

T E REAR

P
Deletion Deletion

N
Insertion Insertion
Input restricted DEQueue

L
FRONT REAR

E
Insertion

T
Deletion
Deletion

P
(a) Input-restricted dequeue

N
Output restricted DEQueue

FRONT

EL
REAR

T
Insertion

P
Insertion
Deletion

N
(b) Output-restricted dequeue
EL
T
Priority Queue

P
N
Priority queue

FRONT

L
REAR

A B .

T
.

E X . . P

P
p p . . p . . p
1 i n

N
2
Priority queue using array
FRONT REAR

L
X X Y Insertion

E
. P. .

T
Deletion Shift one

Deletion

N.
P
FRONT

X ....................

Sort after insertion


REAR

Y
.
Insertion
Priority queue using array
F R

L
. ........ .

E
Priority p
1
F R 1 2 . . . . . . . . . . . . LENGTH
1

T
2
. ........ . 3

P
.
Priority p2 . . ............ Elements having
. priority value i

N
.
F R
i
.
.
. ............. . N N X LENGTH
Priority p
n

(a) Multiple queue with simple queues (b) Multiple queue with a matrix
Priority queue using linked list

L
LLINK DATA PRIORITY RLINK

A 1 B 1

T E
E 1 F 2 K 2

FRONT

L 5

REAR

N P
M 5 P 4 R 4
Priority queue using heap tree

L
P(5)
1

P(5)
5
P(5)
6

T E
P
P(4)
4 P
10 (5)
P(3)
3 P(3)
7

N
P(2)
8
P(1)
9 P(4)
2
EL
P T
Applications of Queue

N
Applications of queue structures

Queues are extensively used in Operating System

1. Simulation

EL
T
2. CPU scheduling in multiprogramming environment

N P
3. Process scheduling
EL
P
For more discussion on stack

T
N
applications see the book
Classic Data Structures
Chapter 4
Prentice Hall of India, 2nd Ed.
EL
PT
N
EL
P T
Data Structures and Algorithms Using Java
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 07: Queue


Lecture 25 : Programming for Queue
EL
T
Ø Implementation of queue using array
Ø Defining a queue using array

P
Ø Operations

N
Ø Implementation of queue using linked list
Ø Defining a queue using linked list
Ø Operations

Ø Applications
Ø CPU Process Scheduling
EL
P T
Implementation of Queue
Using Array

N
Example 25.1: Defining the class queue using array

L
// This program shows how a stack can be defined using an array

E
class QueueA<T>{
T[] data;

T
int front, rear;
int length;

P
QueueA(T[] a){
data = a;
front = 0;

N
rear = -1;
length = a.length;
}
/* The methods enqueue(), dequeue(), isEmpty(), printQueue() are to be defined
here. See the next slides for such method definitions. */
}
Example 25.2: Defining the method enqueue()

L
// This part of the program includes the definition of the enqueue() method

E
// Defining the insert operation
void enque(T a){
if(rear>=length-1){

T
System.out.println("Queue Overflow");
}

P
elss {
rear++;

N
data[rear] = a;
}
}
// The next method dequeue() is to be defined here .... See the next slide
Example 25.3: Defining the method dequeue()

L
// This part of the program includes the definition of the dequeue() method

// Defining the delete operation

E
T deque(){
T x = null;

T
if(isEmpty()){
System.out.println("Queue Underflow");

P
return null;
}
else {

N
x = data[front];
front++;
return x;
}
}
// The next method isEmpty() is to be defined here .... See the next slide
Example 25.4: Defining the method isEmpty()

L
// This part of the program includes the definition of the isEmpty() method

E
boolean isEmpty(){

T
if(front>rear){
return true;

P
}
else{
return false;

N
}
}
// The next method printQueue()is to be defined here .... See the next slide
Example 25.5: Defining the method printStack()

L
// This part of the program includes the definition of the printQueue() method

E
// Defining an operation to print an entire queue content

void printQueue() {

T
if(!isEmpty()) {
for(int i = front;i<=rear;i++) {

P
System.out.print(data[i] + " ");

N
}
System.out.println();
}
} // End of the definition of the class QueueA
Example 25.6: Basic queue operation using the class QueueA

/* This is the main program, illustration the usage of the class defined. You
should include the package, where this program is stored. */

L
class QueueAImplementationDemo {

E
public static void main(String[] args){
Integer arr[] = new Integer[2];
QueueA<Integer> q = new QueueA<Integer>(arr);

T
q.enque(1);

P
q.printQueue();
q.enque(2);
q.printQueue();
q.enque(3);

N
q.printQueue();
q.deque();
q.printQueue();
q.deque();
q.printQueue();
q.deque();
q.printQueue();
}
} // End of the demo class
EL
P T
Implementation of Queue
Using Linked List

N
Example 25.7: Defining the class queue using linked list

L
// This program shows how a queue can be defined using a linked list

E
/* import jLLPacakge;
This program uses linked list related implementation; so, include the

T
directory, where all those programs are defined (e.g. jLLPacakage folder. */

P
class QueueL<T> {
JLinkedList<T> front, rear;
QueueL(){

N
front = new JLinkedList<T>();
rear = front;
}
/* The methods enqueue(), dequeue(), isEmpty(), printQueue() are to be
defined here. See the next slides. */
}
Example 25.8: Defining the method enqueue()

EL
// This part of the program includes the definition of the push() method

T
// Defining the insert operation
void enque(T a){

P
this.rear.insertEnd(a); // Method is in jLLPackage
}

N
// The next method dequeue() is to be defined here .... See the next slide
Example 25.9: Defining the method dequeue()

L
// This part of the program includes the definition of the dequeue() method

E
// Defining the delete operation
T deque(){

T
T data = null;
if(!isEmpty()){

P
this.front.deleteFront(); // Method is in jLLPackage
}
else {

N
System.out.print("Queue Underflow");
}
return null;
}
// The next method isEmpty() is to be defined here .... See the next slide
Example 25.10: Defining the method isEmpty()

L
// This part of the program includes the definition of the isEmpty() method

E
boolean isEmpty() {
if(front.isEmpty()){

T
return true;
}

P
else{
return false;

N
}
}
// The next method printQueue()is to be defined here .... See the next slide
Example 25.11: Defining the method printQueue()

L
// This part of the program includes the definition of the printQueue() method

E
// Defining an operation to print an entire queue content
void printQueue(){

T
if(this.front.isEmpty()){
System.out.println("Queue is Empty");

P
}
else{
this.front.printList();

N
}
}

} // End of the definition of the class StackL


Example 25.12: Basic queue operation using the class QueueL

/* This is the main program, illustration the usage of the class defined. You should

L
include the package, where this program is stored. */

E
class QueueLImplementationDemo {
public static void main(String[] args) {
QueueL<Integer> q = new QueueL<Integer>();

T
q.enque(1);
q.printQueue();

P
q.enque(2);
q.printQueue();
q.enque(3);

N
q.printQueue();
q.deque();
q.printQueue();
q.deque();
q.printQueue();
q.deque();
q.printQueue();
}
} // End of the demo class
EL
P T
Application of Queue

N
Example 25.12: Process scheduling application of queue

/* The following is the class definition to define a process. */

L
class Process {

E
int index;
int time;
Process(int i,int t){

T
time = t;
index = i;

P
}
void print()

N
{
System.out.println("Job:"+ this.index + " time:" + this.time);
}
} // End of the process class

// Continued to next ...


Example 25.12: Process scheduling application of queue

// Continued on...

L
/* The following program is the main class which schedule process according to their

E
priorities. */

class QueueApplicationDemo {

T
public static void main(String[] args) {
Process arr1 = new Process(1,5);
Process arr2 = new Process(2,15);

P
Process arr3 = new Process(3,10);
Process arr4 = new Process(4,35);
Process done;

N
int totaltime = 0;
QueueL<Process> fcfs = new QueueL<Process>();

fcfs.enque(arr1);
fcfs.enque(arr2);
fcfs.enque(arr3);
fcfs.enque(arr4);
System.out.println("Job Entering complete");
// Continued to next...
Example 25.12: Process scheduling application of queue

// Continued on...

L
done = fcfs.deque();

E
done.print();
totaltime+=done.time;

T
done = fcfs.deque();
done.print();
totaltime+=done.time;

P
done = fcfs.deque();
done.print();

N
totaltime+=done.time;

done = fcfs.deque();
done.print();
totaltime+=done.time;

System.out.println("Total time taken is:" + totaltime);


}
} // End of the driver class
EL
P T
Ø Classic Data Structures, Debasis Samanta, 2nd Edition, Prentice Hall of India

N
Ø https://cse.iitkgp.ac.in/~dsamanta/javads/index.html
EL
PT
N

You might also like