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

Data Structure & Algorithm Chapter 4

University Data structure and algorithm in java ppt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Data Structure & Algorithm Chapter 4

University Data structure and algorithm in java ppt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter Four

Stacks and Queues

1
Introduction
▪ Both Stack and Queue are under the category of Linear data structure
▪ In Linear data structure, values are arrange in linear fashion.
▪ Stack: Add to top and remove from top
▪ Queue: Add to back and remove from front
▪ In this chapter, we will see the concept of Stack and Queue one by one:

2
Stack
▪ A simple data structure, in which insertion and deletion occur at the same end, is
termed (called) a stack. It is a LIFO (Last In First Out) structure.
▪ The operations of insertion and deletion are called PUSH and POP Respectively.
✓Push - push (put) item onto stack
✓Pop - pop (get) item from stack
▪ Stack is a Linear data structure working in LIFO manner.
▪ It is an Abstract Data type (ADT), commonly used in most programming
Languages.
▪ In this type of data structure, we can extract the data from the end from which
we enter the data.
▪ Push Operation is used to enter data in stack and Pop Operation is used to
remove data from the stack.
3
Cont’d…
▪ Common terminology or Commands that we use in stacks:
✓Push(Item):To add an Element to the stack
✓Pop: To remove an Element from the stack
✓isEmpty: Return true If the stack is Empty Else return False
✓isFull: Return true If the stack is Full Else return False

4
Stack- Examples

5
Stack Representation

6
Cont’d…

7
Cont’d…
▪ We need to know TOS(Top of Stack)
▪ Operations done on stack
▪ Push--- Insert Element at TOS
▪ Pop---Remove Element from TOS

8
Cont’d…

9
Algorithm for Insert Data in to a Stack

▪ Step 1:- Check Stack is Full


If Top=Max-1
Print Stack is Full and exit
▪ Step 2:- Increment to by one
TOP=TOP+1
▪ Step 3:- Insert Data in to stack
Stack[TOP]=data
▪ Step 4:- End

10
Push(Insert data Item into Stack)
▪ For Inserting data Item into Stack, we use Push Operation.
▪ Data 1, Data 2, Data 3, Data 4

11
Algorithm for Remove Data from Stack
▪ Step 1:- Check Stack is Empty
If Top= -1
Print Stack is Empty and exit
▪ Step 2:- Delete an Element from stack Top
Set Del_element=Stack[TOP]
▪ Step 3:- Decrement stack size by one
TOP=TOP-1
▪ Step 4:- End

12
Pop(Deleting data Item from Stack)
▪ For Deleting data Item from Stack, we use pop Operation.
▪ Data 1, Data 2, Data 3, Data 4

13
Stack-Implementation
▪ Stacks can be Implemented both as an Array (Contiguous list) and as a Linked List.
▪ We want a set of Operations that will work with either a type of Implementation: i.e the
method of Implementation is Hidden and can be changed without affecting the programs that
use them.
Push()
{
If there is a room // If there is a Space
{
Put an Item on the top of the Stack
}
Else
{
Give an Error message //Stack Overflow or Stack already full
}} 14
Cont’d…
Pop()
{
If stack not empty //If the stack Contains an Element or not
{
Return the value of the top Item to the user and remove the top item
from the stack
}
Else
{
Give an Error message //Stack is underflow
}}

15
Application of Stacks
1. Evaluation of Algebraic Expressions
▪ Re-expressing the Expression(in the form of easily understandable by the
compiler):- In order to solve Arithmetic Expressions, Computers restructure them so that the
results of each computation are incorporated within the Expression. Once transformed, an
Expression can be solved one step.
Types of Expression
▪ The normal (or human) way of expressing mathematical expressions is called
infix form, e.g. 4+5*5. i.e Ans=29
▪ However, there are other ways of representing the same expression, either by
writing all operators before their operands or after them,
▪ e.g.
4 5 5 * + //N.B 4,5,5 is called Operands and +,*,= is called Operators
+4*55 16
Cont’d…
455*+
▪ In this case If the Operand comes before the Operator (* and +) we call it
postfix.
+4*55
▪ In this case If the Operator comes before the Operand (+ and *) we call it
Prefix.
▪ But If the Operator comes between the Operand like 4+5*5, we call it Infix: it is
natural or mire adapted by human beings.
▪ Postfix and Prefix Notations like:
455*+
+4*55
▪ This method is called Polish Notation (because this method was discovered by
the Polish mathematician Jan Lukasiewicz). 17
Cont’d…
▪ When the operators are written before their operands, it is called the Prefix form. This means
that At least one Operator comes before the Operand, but In between there may by another
operators.
• e.g. + 4 * 5 5
▪ When the operators come after their operands, it is called Postfix form (suffix form or
reverse polish notation). This means that At least one Operator comes after the Operand, but I
between there may by another operators.
• e.g. 4 5 5 * +

18
Cont’d…
The valuable aspect of RPN (Reverse Polish Notation or postfix )
✓Parentheses are unnecessary or ()
✓Easy for a computer (compiler) to evaluate an arithmetic expression Postfix (Reverse
Polish Notation)
▪ Postfix notation arises from the concept of post-order traversal of an expression tree ( this
concept will be covered when we look at trees).
▪ For now, consider postfix notation as a way of redistributing operators in an expression so that
their operation is delayed until the correct time.

19
Purpose of Postfix
▪ Infix Notation cannot be used to evaluate expressions in high level Languages.
▪ To decide how to assess an expression, we must first analyze it.
▪ An approach that is frequently used is to transform an Infix Notation to Postfix Notation
before evaluating It.
Syntax
▪ Operands are Immediately sent to the Output.
▪ The stack is pushed using Operators, including Parentheses.
▪ Determine whether the current Operator is less than the stack top Operator, If the top operator
is less than, Place the current operator on the stack.
▪ Current Operator is pushed into the stack and the top operator is popped if the top operator is
bigger than (or equal to) the current
▪ Pop from the stack until we finish a matching left parentheses if we come across a right
parentheses. Don’t print Parentheses.// Don’t store parentheses in the output
20
Cont’d…
Operator Priority in Order of Precedence:
1. Parentheses() have high priority
2. All Unary Operators(sine, cosine..)
3. Division and Multiplication / *…if they come once= perform Left to write
4. Addition and Subtraction + - …if they come once= perform Left to write

21
Queues
▪ A Data structure that has access to its data at the front and rear/back/.
▪ Operates on FIFO (Fist In First Out) basis.
▪ LILO Refers to Last In, Last Out Equivalent to FIFO
▪ Uses two pointers/indices to keep track of information/data (i.e front and rear)
Has two basic operations:
▪ Enqueue - inserting data at the rear of the queue
▪ Dequeue – removing data at the front of the queue

OR
22
Cont’d…
▪ Example:

23
Simple array implementation of enqueue
and dequeue operations
▪Analysis:
▪ Consider the following structure: int Num[MAX_SIZE];// Num is name of queue
▪ We need to have two integer variables that tell:
1. The index of the front element //to show the exact location of front
2. The index of the rear element //to show the exact location of front
▪ We also need an integer variable that tells: // total size of the queue
✓the total number of data in the queue
▪ int FRONT =-1,REAR =-1;
▪ At the very beginning we should declare locally or globally Front=-1 & Rear=-1
▪ Since we don’t add any data to the queue F & R=-1, B/C there is no Index less than 0.
▪ int QUEUESIZE=0; // There is no any element in the queue
24
To enqueue data to the queue
▪ Check if there is a space in the queue
▪ REAR<MAX_SIZE-1? // MAX_SIZE=N=total Element
Yes/True: Increment REAR
• Store the data in Num[REAR]
• Increment QUEUESIZE
• FRONT = = -1? // initially it was no data, so increment the
Front by 1. i.e -1+1=0. our front is at 0 index
• Yes: - Increment FRONT // from -1 to 0
No/False: - Queue Overflow // no space in the queue, If we add new
data Overflow will occur

25
To dequeue data to the queue
▪ Check if there is data in the queue
▪ QUEUESIZE > 0 ?
▪ Yes: - Copy the data in Num[FRONT]
• Increment FRONT
• Decrement QUEUESIZE
▪ No: - Queue Underflow // There is no data in the queue

26
Implementation
const int MAX_SIZE=100;
int FRONT =-1, REAR =-1;
int QUEUESIZE = 0;
void enqueue(int x)
{
if(Rear<MAX_SIZE-1)
{
REAR++;
Num[REAR]=x;
QUEUESIZE++;
if(FRONT = = -1)
FRONT++;
}
else
cout<<"Queue Overflow";
} 27
Cont’d…
int dequeue()
{
int x;
if(QUEUESIZE>0)
{
x=Num[FRONT];
FRONT++;
QUEUESIZE--;
}
else
cout<<"Queue Underflow";
return(x);
}
28

You might also like