0% found this document useful (0 votes)
24 views86 pages

Download

Uploaded by

Biplab Ray
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views86 pages

Download

Uploaded by

Biplab Ray
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

UNIT II – STACKS AND QUEUES

Stack ADT – Operations - Applications -


Evaluating arithmetic expressions- Conversion of
Infix to postfix expression - Queue ADT –
Operations - Circular Queue – Priority Queue -
deQueue – applications of queues.
STACK
 Stack is an important data structure which stores its
elements in an ordered manner.
 A stack is a linear data structure in which the elements
in a stack are added and removed only from one end,
which is called the TOP.
 A stack is called a LIFO (Last-In-First-Out) data structure.
 As the element that was inserted last is the first one to
be taken out.
STACK
 Initial Value of TOP is -1.
OPERATIONS ON STACK
 PUSH
 The process of inserting a new element into the top of the
stack.
 For every PUSH operation TOP is incremented by 1.
 PUSH = TOP +1.
OPERATIONS ON STACK
 POP
 The process of deleting an element from the top of stack is
called POP operation.
 For every POP operation TOP is decremented by 1.
 POP=TOP-1.

 PEEK - Peek is an operation that returns the value of the


topmost element of the stack without deleting it from
the stack.
EXCEPTIONAL CONDITIONS
 Overflow – Attempt to insert an element into the stack,
when the stack is full is said to be Overflow.

 Underflow – Attempt to delete an element from the


stack, when the stack is empty is said to be Underflow.
IMPLEMENTATION OF STACK
Stack can be implemented in two ways

 1. Array Implementation

 2.Pointer or Linked List Implementation


ARRAY IMPLEMENTATION
 In this implementation each stack is associated with a
top pointer, which is -1 for an empty stack.

 To PUSH an element X onto the stack, TOP pointer is


incremented and then set Stack [TOP]=X;

 To POP an element, the Stack [TOP] value is returned


and the TOP pointer is decremented.
ROUTINE TO PUSH AN ELEMENT
Void Push(int X, Stack S)
{
If(IsFull(S))
Error (“Stack is Full”);
else
{
Top= Top+1;
S[Top] =X;
}
int IsFull(Stack S)
{
if(Top==Arraysize)
return (1);
}
}
ROUTINE TO POP AN ELEMENT
Void Pop(Stack S)
{
if(IsEmpty(S))
Error(“Stack is Empty”);
else
{
X=S[Top];
Top= Top-1;
}

}
int IsEmpty(Stack S)
{
if(Top==-1)
return 1;
}
ROUTINE TO RETURN TOP ELEMENT
int TopElement(Stack S)
{
if(!IsEmpty(S))
return S[Top];
else
Error(“Empty Stack”);
return 0;
}
LINKED LIST IMPLEMENTATION
 PUSH operation is performed by inserting an element at
the front of the list.

 POP operation is performed by deleting at the front of


the list.

 TOP operation returns the element at the front of the


list.
EXAMPLE
STRUCTURE DECLARATION
Struct Node
{
int Element;
Struct Node *Next;
}
-----------------------------------------------------------------------------

Note: SNext = TOP


ROUTINE TO PUSH AN ELEMENT ONTO A STACK
void Push(int X, Stack S)
{
Struct Node *Tempcell;
Tempcell = malloc(sizeof(Struct Node));
if(Tempcell==NULL)
Error(“OutofSpace”);
else
{
TempcellElement = X;
TempcellNext=SNext;
SNext = Tempcell;
}
}
EXAMPLE

100
ROUTINE TO POP AN ELEMENT FROM A STACK
void Pop (Stack S)
{
Struct Node *Tempcell;
If (IsEmpty(S))
Error (“Empty Stack”);
else
{
Tempcell=SNext;
SNext=SNextNext;
Free (Tempcell);
}
}
EXAMPLE

SNextNext : SNext =400 then 400Next=300


ROUTINE TO RETURN TOP ELEMENT OF A STACK
int Top(Stack S)
{
if(!IsEmpty(S))
return SNextElement;
Error (“Empty Stack”);
return 0;
}
APPLICATIONS OF STACK
 Evaluating Arithmetic Expression

 Balancing the symbols (Parenthesis)

 Towers of Hanoi

 Function Calls

 8 Queen Problem
NOTATIONS TO REPRESENT ARITHMETIC EXPRESSION

 Infix: Operators are placed in between the operands


Ex: a+b

 Prefix: Operators are placed before the operands


Ex:+ab

 Postfix: Operators are placed after the operands.


Ex:ab-
EVALUATING ARITHMETIC EXPRESSION
 Infix to Postfix Conversion

 Evaluating Postfix Expression

Priority Order

 First Priority - ^ (Higher Order Priority)

 Second Priority - /,*

 Third Priority - +,-


INFIX TO POSTFIX CONVERSION
 If the character is an operand, place it onto the output.
 If the character is an operator, push it onto the stack.
 If the stack operator has a higher or equal priority than
input operator then POP that operator from the stack
and place it onto the output.
 If the character is left parenthesis, PUSH it onto the
stack.
 If the character is a right parenthesis, POP all the
operators from the stack till it encounters left
parenthesis, discard both the parenthesis in the output.
ALGORITHM
EXAMPLE - 1
EXAMPLE - 2
EXAMPLE - 3
EVALUATING POSTFIX EXPRESSION
 If the character is an operand, PUSH its associated value
onto the stack.

 If the character is an operator, POP two values from the


stack, apply the operator to them and push the result
onto the stack.
ALGORITHM
EXAMPLE - 1
EXAMPLE – 2 EVALUATE 636+5*9/-
BALANCING THE SYMBOLS
 If the character is an opening symbol, PUSH it onto the
stack.
 If the character is a closing symbol and if the stack is
empty report an error as missing opening symbol.
 If it is a closing symbol and if it has corresponding
operating symbol in the stack, POP it from the stack.
Otherwise report an error as mismatched symbols.
 At the end of file, if the stack is not empty, report an
error as Missing closing symbol. Otherwise, report as
balanced symbols.
EXAMPLE
TOWERS OF HANOI
 It is one of the example illustrating the Recursion
Technique.
 The problem is moving a collection of N disks of
decreasing size from one pillar to another pillar.
RULES
 1.Only one disk could be moved at a time.

 2.No larger disk could ever reside on a pillar on top of a


smaller disk.
 3.A 3rd pillar could be used as an intermediate to store
one or more disks, while they were being moved from
source to destination.
ROUTINE FOR TOWERS OF HANOI
void Hanoi(int n, char s, char d, char i)
{
if(n==1)
{
print(s,d);
return;
}
else
{
Hanoi(n-1,s,i,d);
print(s,d);
Hanoi(n-1,i,d,s);
return;
}
}
EXAMPLE
FUNCTION CALLS
 When there is a function call, all the important
information that needs to be saved, such as register
values (corresponding to variable names) and the return
address (which can be obtained from the program
counter).
 The information saved is called either an activation
record or stack frame.
 The current environment is represented at the top of
the stack.
RECURSIVE FUNCTION TO FIND FACTORIAL
int Fact(int n)
{
int s;
if(n==1)
return 1;
else
s=n*Fact(n-1);
return(s);
}
EXAMPLE
8 QUEEN PROBLEM
 The 8 Queen problem is the problem of placing 8
Queens on an 8X8 board.

 Such that none of them attack another.

 That is no two are in the same row, column or diagonal.


EXAMPLE – 4 QUEEN
EXAMPLE – 8 QUEEN
QUEUE
 Queue is a Linear DS.
 A Queue is a FIFO (First-In, First-Out) data structure in
which the element that is inserted first is the first one to
be taken out.
 The elements in a queue are added at one end called
the REAR.
 The elements are removed from the other end called
the FRONT.
QUEUE
 Initial Conditions: FRONT = 0 and REAR = -1.

Examples
 People moving on an escalator. The people who got on
the escalator first will be the first one to step out of it.
 People standing outside the ticketing window of a
cinema hall. The first person in the line will get the ticket
first and thus will be the first one to move out of it.
OPERATIONS ON QUEUE
 Enqueue - The process of inserting an element in the
queue. For every Enqueue operation in the Queue REAR
pointer is incremented by 1.
OPERATIONS ON QUEUE
 Dequeue - The process of deleting an element from the
queue. For every Dequeue operation in the Queue
FRONT pointer is incremented by 1.
EXCEPTIONAL CONDITIONS
 Overflow: Attempt to insert an element into the Queue
when Queue is full is called Overflow.

 Underflow: Attempt to delete an element from the


Queue when Queue is empty is called underflow.
IMPLEMENTATION OF QUEUE
Queue can be implemented in two ways

 Array Implementation

 Linked List Implementation[Pointers]


ARRAY IMPLEMENTATION
 Queue is associated with two pointers namely REAR and
FRONT pointer.

 To insert an element X onto the Queue, the REAR


pointer is incremented by 1 and then set Q[REAR]=X.

 To delete an element, the Queue[FRONT] is returned


and FRONT pointer is incremented by 1.
ROUTINE TO ENQUEUE
void Enqueue (int X)
{
if(REAR>=MaxArraySize)
print(“Queue Overflow”);
else
{
REAR=REAR+1;
Q[REAR]=X;
}
}
EXAMPLE
ROUTINE TO DEQUEUE
void Dequeue()
{
if(FRONT<0)
print(“Queue Underflow”);
else
{
X=Q[FRONT];
if(FRONT==REAR)
{
FRONT=0;
REAR=-1;
}
else
FRONT=FRONT+1;
}
}
EXAMPLE
LINKED LIST IMPLEMENTATION [POINTERS]
 Enqueue operation is performed at the end of the list.
 Dequeue operation is performed at the front of the list.
Node Declaration:
Struct Node
{
int Element;
Struct Node *Next;
}*FRONT =NULL,*REAR=NULL; //Initial Condition
ROUTINE TO ENQUEUE AN ELEMENT
Void Enqueue (int X, Queue Q)
{
Struct node *Newnode;
Newnode=malloc (sizeof (Struct node));
if(REAR==NULL)
{
FRONT=Newnode;
REAR=Newnode;
}
else
{
Newnode->Element = X;
Newnode->Next = NULL;
REAR->Next = Newnode;
REAR = Newnode;
}
}
EXAMPLE
Initial Condition REAR=FRONT=NULL
ROUTINE TO DEQUEUE AN ELEMENT
Void Dequeue()
{
Struct Node *Temp;
if(FRONT==NULL)
Error(“Queue is Underflow”);
else
{
Temp = FRONT;
if(FRONT==REAR)
{
FRONT=NULL;
REAR= NULL;
}
else
{
FRONT=FRONT->Next;
free(Temp);
}
}
}
EXAMPLE
CIRCULAR QUEUE
 Circular Queue is Queue in which the first element is
stored immediately after last element.

 If the last location of the queue is occupied, the new


element is inserted at the first memory location of
queue implementing an array(queue).

 A circular Queue overcomes the limitation of the simple


queue by utilizing the entire space of the queue.
CIRCULAR QUEUE
 The FRONT end of the queue always points to the first
element of the queue.
 If the values of FRONT and REAR are equal the queue is
empty.
 The values of FRONT and REAR pointers are only increased
or decreased after insertion and deletion operation.
 Like simple queue, REAR pointer is incremented by one
when a new element is inserted and FRONT pointer in
incremented by one when an element is deleted.
CIRCULAR QUEUE REPRESENTATION
OPERATIONS ON CQUEUE
Two operation can be performed on CQueue

 Enqueue

 Dequeue
POSITION CALCULATION
 Insertion: To perform the insertion of an element to the
queue, the position of the REAR pointer is calculated by the
relation as
REAR = (REAR+1) % Maxsize.
CQueue[REAR]=value.

 Deletion: To perform the deletion, the position of the FRONT


pointer is calculated by the relation.
Value = CQueue[FRONT].
FRONT=(FRONT+1) % Maxsize.
ROUTINE TO CENQUEUE
void CEnqueue(int X)
{
if(FRONT==(REAR+1)%Maxsize)
print(“Queue is Overflow”);
else
{
if(FRONT==-1)
FRONT=REAR=0;
else
REAR=(REAR+1)%Maxsize;
CQueue[REAR]=X;
}
}
EXAMPLE
ROUTINE TO CDEQUEUE
int CDeQueue()
{
if(FRONT==-1)
print (“Queue is Underflow”)
else
{
X=CQueue[FRONT];
if(FRONT==REAR)
FRONT=REAR=-1;
else
FRONT=(FRONT+1)%Maxsize
}
return X;
}
EXAMPLE
EXAMPLE
EXAMPLE
DEQUEUE – DOUBLE ENDED QUEUE
 A Dequeue (pronounced as ‘deck’ or ‘dequeue’) is a list
in which the elements can be inserted or deleted at
either end.

 It is also known as a head-tail linked list because


elements can be added to or removed from either the
FRONT (head) or the REAR (tail) end.

 No element can be added and deleted from the middle.


DEQUEUE
TYPES OF DEQUEUE
 Input restricted Deque : In this dequeue, insertions can
be done only at one of the ends, while deletions can be
done from both ends.

 Output restricted Deque: In this dequeue, deletions can


be done only at one of the ends, while insertions can be
done on both ends.
PRIORITY QUEUE
 A priority queue is a data structure in which each
element is assigned a priority.
 The priority of the element will be used to determine
the order in which the elements will be processed.
 The general rules of processing the elements of a
priority queue are
 Rule 1 : An element with higher priority is processed
before an element with a lower priority.
 Rule 2: Two elements with the same priority are
processed on a first-come-first-served (FCFS) basis.
PRIORITY QUEUE
 A priority queue can be thought of as a modified queue
in which when an element has to be removed from the
queue, the one with the highest-priority is retrieved
first.

 The priority of the element can be set based on various


factors.
PRIORITY QUEUE USING LINKED LIST
 If we are using a sorted linked list, then the element
with the higher priority will precede the element with
the lower priority.
 Lower priority number means higher priority. For
example, if there are two elements A and B, where A
has a priority number 1 and B has a priority number 5,
then A will be processed before B as it has higher
priority than B.
PRIORITY QUEUE USING LINKED LIST
 A priority queue can be represented using arrays or
linked lists.

 When a priority queue is implemented using a linked


list, then every node of the list will have three parts:

(a)The information or data part

(b)The priority number of the element and

(c)The address of the next element.


ENQUEUE OPERATION
 When a new element has to be inserted in a priority queue,
we have to traverse the entire list until we find a node that
has a priority lower than that of the new element.

 The new node is inserted before the node with the lower
priority.

 However, if there exists an element that has the same


priority as the new element, the new element is inserted
after that element.
EXAMPLE
Before Insertion:

Node to be inserted: Data = F Priority = 4

After Insertion:
EXAMPLE
Before Insertion:

Node to be inserted: Data = F , Priority = 2

After Insertion:
DEQUEUE OPERATION
 Deletion is a very simple process in this case.

 The first node of the list will be deleted and the data of
that node will be processed first.
ARRAY REPRESENTATION OF A PRIORITY QUEUE

 When arrays are used to implement a priority queue, then a


separate queue for each priority number is maintained.

 Each of these queues will be implemented using circular


arrays or circular queues.

 Every individual queue will have its own FRONT and REAR
pointers.

 We use a two-dimensional array for this purpose where each


queue will be allocated the same amount of space.
INSERTION OPERATION IN PRIORITY QUEUE
 Insertion

 To insert a new element with priority K in the priority


queue,

 Add the element at the REAR end of row K, where K is


the row number as well as the priority number of that
element.
EXAMPLE
 For example, if we have to insert an element R with
priority number 3, then the priority queue will be given
as,

 Before Insertion:

 After Insertion:
DELETION OPERATION IN PRIORITY QUEUE
 To delete an element, we find the first non-empty queue
and then process the FRONT element of the first non-
empty queue.
 In our priority queue, the first non-empty queue is the
One with priority number 1 and the FRONT element is
A, so A will be deleted and processed first.
 In technical terms, find the element with the smallest K,
such that FRONT [K]! = NULL.
APPLICATIONS OF QUEUE
 Batch Processing in Operating System.

 To Implement Priority Queues.

 Priority Queues can be used to sort the elements using


Heap Sort.

 Simulation.

 Mathematics using Queuing Theory.

 Computer Networks.
STACK VS QUEUE
S. No Terms Stack Queue
1. Principle First In First Out – LIFO Last In First Out - FIFO
2. Pointer Top Front and Rear
3. Operation Push and Pop Enqueue and Dequeue
Both Push and Pop Enqueue – Rear
4. Operation End Operations are performed Dequeue – Front
at Top
Exceptional Overflow and Underflow Overflow and Underflow
5.
Conditions
Top = -1. Rear = 0, Front = -1.
6. Initial Condition
Front=Rear=NULL
Push = Top+1 Enqueue = Rear+1
7.. Pointer Changing
Pop= Top-1 Dequeue = Front+1
1. Array 1. Array
8. Implementation 2. Linked List 2. Linked List

You might also like