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

Unit-2 Notes Stack Queue DKPJ-1

The document discusses stacks and queues as abstract data types. It describes stack operations like push and pop and implementations using arrays and linked lists. Stacks follow LIFO order while queues follow FIFO. Common stack applications include evaluating expressions and recursion. Iteration is compared to recursion, noting tradeoffs. Queues support create, add, delete, empty and full operations and have circular queue and priority queue variations. Detailed examples are given of stack representations and push/pop algorithms in C code.

Uploaded by

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

Unit-2 Notes Stack Queue DKPJ-1

The document discusses stacks and queues as abstract data types. It describes stack operations like push and pop and implementations using arrays and linked lists. Stacks follow LIFO order while queues follow FIFO. Common stack applications include evaluating expressions and recursion. Iteration is compared to recursion, noting tradeoffs. Queues support create, add, delete, empty and full operations and have circular queue and priority queue variations. Detailed examples are given of stack representations and push/pop algorithms in C code.

Uploaded by

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

BCS301 DATA STRUCTURE

Notes- Stack & Queue


UNIT-II
Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and Linked Implementation of Stack in C,
Application of stack: Prefix and Postfix Expressions, Evaluation of postfix expression, Iteration and Recursion-
Principles of recursion, Tail recursion, Removal of recursion Problem solving using iteration and recursion with examples
such as binary search, Fibonacci numbers, and Hanoi towers. Tradeoffs between iteration and recursion.
Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues, Array and linked implementation of
queues in C, Dequeue and Priority Queue.

What is Stack? Explain With example.


A stack is a linear data structure in which an element may be inserted or deleted only at one end,
called the top of the stack. That is elements are removed from a stack in the reverse order of
insertion. Thus stacks are also called LIFO(Last In First Out) lists.
The following figure shows a real-life example of such a structure:.

a stack of boxes a deck of cards a pile of plates,


What kind of operation you can do with above example?
Only you can insert or delete an item from top.
Basic Operations on Stack
There are three basic operations on a stack.
• PUSH – Inserting an element into a stack.
• POP – Deleting an element from a stack.
• PEEK – Returns the topmost element of the stack.
Both PUSH, POP and PEEK operations are performed on the top of the stack.
Stack Conditions
Empty Condition : No element exits in stack
Full Condition: No new element can enter into the stack
Overflow Condition: if we try to enter element into the stack
Underflow Condition: if try to delete an element from the stack
PUSH Operation on a Stack
Inserting a new element in the TOP of the stack is called the PUSH operation. We must check if the
stack is full before insertion. After PUSH operation the TOP will point to the newly inserted item.
In the following figure, item 7 will be added into the stack on the top of item 6 and after insertion,
the TOP pointer will point to item 7.

1
PUSH OPeration on a Stack

Stack Overflow Condition


In computer programs, the size of the stack is predefined. If we try to insert a new element into a full
stack, then the stack overflow condition will occur.

POP Operation on a Stack


The POP operation deletes an element from the top of the stack. We must check if the stack is empty
before deletion. The value of TOP will be decremented by one after the POP operation. In the figure,
item 6 will be removed from the stack and now the TOP will be pointing to item 5.

POP Operation on a Stack


Stack Underflow Condition
Stack underflow condition occurs when we try to remove an item from an empty stack.

PEEK Operation on a Stack


Peek is an operation that returns the value of the topmost element of the stack. This operation doesn’t
delete the element.

PEEK Operation
Here the PEEK operation will return the value 7 without deleting it.

Representation of Stacks
Stack is usually represented by means of a linear array or a one-way linked list.

Array Representation of Stacks


Stacks can be maintained in a program by using a linear array of elements and pointer
variables TOP and MAX. The TOP pointer contains the location of the top element of the stack and
MAX gives the maximum number of elements in the stack.
The stack is empty if TOP=-1 or TOP=NULL. The following figure shows an array representation of
the stack.

Stack Representation Using Array


2
TOP=3 indicates that the stack has four elements(0 to 3). Since MAX-1=9, there is space for 6 more
elements in the stack.
The PUSH and POP operations can be implemented in a stack by the following algorithms.

PUSH(STACK, TOP, MAX, ITEM)


Algorithm Push(STACK,TOP,MAX,ITEM)
1. If TOP=MAX-1, then Print: OVERFLOW, and Return
2. Set TOP=TOP+1
3. Set STACK[TOP]=ITEM
4. Return

POP(STACK, TOP, ITEM)


Algorithm Push(STACK,TOP,ITEM)
1. If TOP=-1, then Print: UNDERFLOW, and Return
2. Set ITEM=STACK[TOP]
3. Set TOP=TOP-1
4. Return

PEEK(STACK, TOP)
Algorithm Push(STACK,TOP)
1. If TOP=-1, then Print: UNDERFLOW, and Return
2. RETURN STACK[TOP]

These three operations can be implemented in C as follows


void push()
{
if (top == MAX - 1)
{
printf("\n STACK OVERFLOW");
}
else
{
top++;
st[top] = val;
}
}

int pop()
{
int val;
if (top == -1)
{
printf("\n STACK UNDERFLOW");
return -1;
}
else
{
val = st[top];
top--;
return val;
}
}
3
void display()
{
int i;
if (top == -1)
printf("\n STACK IS EMPTY");
else
{
for (i = top; i >= 0; i--)
printf("\n %d", st[i]);
}
}

int peek()
{
if (top == -1)
{
printf("\n STACK IS EMPTY");
return -1;
}
else
return (st[top]);
}

Push Example

POP Example

4
Linked Representation of Stack

The disadvantage of using an array to represent a stack is that the array must be specified to have a
fixed size. If the size of the array can’t be determined in advance, we can use the linked
representation of the stack.
The HEAD pointer of the linked list is used as the TOP of the stack.

Linked Representation of Stack

The PUSH and POP operations can be implemented in a stack by the following algorithms.

PUSH_LINK(TOP, ITEM)
Algorithm PushLink(TOP,ITEM)
1. Allocate memory for the new node and name it as NEW
2. Set NEW->DATA=ITEM
3. IF TOP==NULL
SET NEW->NEXT=NULL
SET TOP=NEW
ELSE
SET NEW->NEXT=TOP
Set TOP=NEW
[END OF IF]
6. Exit.

The operation is the same as inserting a new node at the beginning of a linked list.

PUSH Operation in a Stack Using Linked List

5
Block of code in C
void push ()
{
int val;
struct node *ptr =(struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed");
}
}

POP_LINK(TOP, ITEM)
Algorithm PushLink(TOP,ITEM)
1. IF TOP=NULL then Write UNDERFLOW and Exit
2. Set ITEM=STACK->DATA
3. Set TEMP=TOP and TOP=TOP->LINK
4. FREE TEMP
5. Exit

The operation is the same as deleting a node from the beginning of a linked list.

POP Operation in a Stack Using Linked List

6
Block of code in C

void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
}
Block of code in C

void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}
}
}

Applications of Stack

• Evaluating Expressions.
• Converting between expressions.
• Back tracking.
• Parsing context-free languages.
• Recursion removal.
• Tree and graph traversal.

7
Polish Notation
Algebraic expressions can be written using three separate but equivalent notations
namely infix, postfix, and prefix notations.

Infix Notation(Polish notation)


The operator symbol is placed between its two operands in most arithmetic operations. This is
called infix expression.
For example, (A + B) ;
here the operator + is placed between the two operands a and b.
Although we find it simple to write expressions in infix notation, computers find it difficult to
parse. So, the computer normally evaluates arithmetic expressions written in infix notation after
converting them into postfix notation. The stack is the primary tool used to complete the given
task in each phase.

Prefix Notation (Polish Notation)


Computers perform better when expressions are written in prefix and postfix notations.
Prefix notation refers to the notation in which the operator is placed before its two operands. For
example, if
A + B is an expression in infix notation,
then
+AB is the equivalent expression in prefix notation.

Postfix Notation (Reverse Polish Notation)


In postfix notation, the operator is placed after the operands. For example, if an expression is
written in infix notation as
A + B , it can be written in postfix notation as AB+
.
The evaluation of a postfix and prefix expressions are always performed from left to right.

Evaluation of a Postfix Expression or reverse polish notation


The following algorithm is used to evaluate the value of a postfix expression.

Algorithm EvaluationPostfix(Postfix Expression)


1. Add a “)” at the end of the post fix expression
2. Scan every character of the postfix expression and repeat Steps 3 and 4 until “)” is
encountered
3. If an operand is encountered then push it on the STACK.
4. If an operator O is encountered, then
1. POP the two top elements of STACK as A (topmost element) and B(next-to-top
element).
2. Evaluate B O A.
3. Push the result of evaluation on the STACK.
5. SET RESULT equal to the topmost element of the STACK.

8
Example-1
Consider the following postfix notation
823*8+2/–
The equivalent infix expression is
8 – ((2 * 3) + 8) / 2
The following table shows the procedure for evaluating the expression by simulating the above
algorithm.

Symbol Scanned STACK


8 8
2 8, 2
3 8, 2, 3
* 8, 6
8 8, 6, 8
+ 8, 14
2 8, 14, 2
/ 8, 7
– 1
The final number in the stack, 1, is the value of the postfix expression.

Example-2
Now let us consider the following infix expression 2 * (4+3) - 5.
Its equivalent postfix expression is 2 4 3 + * 5.
The following step illustrates how this postfix expression is evaluated.

9
Block of code in C

void EvalPostfix(char postfix[])


{

int i;
char ch;
int val;
int A, B;

for (i = 0; postfix[i] != ')'; i++) {


ch = postfix[i];
if (isdigit(ch)) {

push(ch);
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {

A = pop();
B = pop();

switch (ch) /* ch is an operator */


{
case '*':
val = B * A;
break;

case '/':
val = B / A;
break;

case '+':
val = B + A;
break;

case '-':
val = B - A;
break;
}

push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}

Conversion of an Infix Expression into a Postfix Expression


For the sake of simplicity, we will only use the +, –, *, /, and % operators. The order of
precedence of these operators is as follows:
• Higher priority *, /, %
• Lower priority +, –

10
The algorithm below converts an infix expression to a postfix expression.
Algorithm InfixToPostfix(Infix Expression)
1. Push "(" on to the stack, and add ")" to the end of infix expression.
2. Repeat until each character in the infix notation is scanned
• IF a "(" is encountered, push it on the stack.
• IF an operand is encountered, add it to the postfix expression.
• IF a ")" is encountered, then
1. Repeatedly pop from stack and add it to the postfix expression until a "(" is
encountered.
2. Discard the "(" . That is, remove the "(" from stack and do not add it to the
postfix expression.
• IF an operator O is encountered, then
1. Repeatedly pop from stack and add each operator (popped from the stack)
to the postfix expression which has the same precedence or a higher
precedence than O.
2. Push the operator O to the stack.
3. Repeatedly pop from the stack and add it to the postfix expression until the stack is
empty.

Example-1
Convert the infix expression
A+ (B*C )
into postfix expression.

Infix Character Scanned Stack Postfix Expression

(
A ( A
+ (+ A
( (+( A
B (+( AB

* (+(* AB
C (+(* ABC

) ABC*+

11
Example -2
Converting an infix expression into a postfix expression.

Exercise:
Infix Prefix postfic

(A + B) × (C + D) × + AB + CD. ?

A × B + A × (B × D + C × E) + × AB × A + × BD × CE. ?

A × {B + C × (D + E)} / F × (G + H) / × A + B × C + DE × F + GH. ?

A×B+C×D+E×F ? AB × CD × + EF × +.

A – B + C × (D × E – F)} / G + H × K ? AB – C DE × F – × + G HK × + /.

12
Block of code in C
int covertInfixToPostfix (char *expression)
{
int i, j;

for (i = 0, j = -1; expression[i]; ++i)


{
if (checkIfOperand (expression[i]))
expression[++j] = expression[i];

else if (expression[i] == '(')


push (expression[i]);
else if (expression[i] == ')')
{
while (!isEmpty () && peek () != '(')
expression[++j] = pop ();
if (!isEmpty () && peek () != '(')
return -1; // invalid expression
else
pop ();
}
else // if an opertor
{
while (!isEmpty ()
&& precedence (expression[i]) <= precedence (peek ()))
expression[++j] = pop ();
push (expression[i]);
}

}
while (!isEmpty ())
expression[++j] = pop ();

expression[++j] = '\0';
printf ("%s", expression);
}

Recursion Using Stack with Example


A function that calls itself is called a recursive function and this technique is called recursion. A
recursive function will call itself until a final call that does not require a call to itself is made. It
takes advantage of the system stack to temporarily store the calling function’s return address and
local variables.
There are two major cases in any recursive solution. They are
• Base case in which the problem is simple enough to be solved directly without the need
for any more calls to the same function
• Recursive case
• The problem at hand is initially subdivided into simpler sub-parts.
• The function calls itself again, but this time with sub-parts of the problem obtained
in the first step.
• The final result is obtained by combining the solutions of simpler sub-parts.
A recursive function is said to be well-defined if it has the following two properties:
• There must be a base criteria in which the function doesn’t call itself.
• Every time the function is called itself, it must be closer to the base criteria.

13
Factorial Function
To illustrate recursive functions, consider calculating the factorial of an integer.
The product of the positive integers from 1 to n is called n factorial denoted by
n!
. To find n!, multiply the number by the factorial of the number that is one less than the
number.
That is,
n! = n * (n - 1)!
Assume we need to find the value of 5!.
Then,
5! = 5 * 4!
, where
4! = 4 * 3!
Therefore,
5! = 5 * 4 * 3!
Expanding further, we get
5! = 5 * 4 * 3 * 2 * 1!
We can now write a recursive function that computes the factorial of a number. Here the
base case is when
n=1
, because the result will be 1 as
1! = 1
. The recursive case of the factorial function will call itself, but with a smaller value of n, as
factorial(n) = n factorial (n–1).

Working of the factorial function using recursion

Example: Factorial of a given number


#include <stdio.h>
int Fact(int);
int main()
{
int num, val;
//read a number from the user
printf("Enter the number: ");
scanf("%d", &num);
//call fact function
14
val = Fact(num);
//print result
printf("Factorial of %d = %d", num, val);
return 0;
}

//function to calculate factorial


int Fact(int n)
{
if (n == 1)
return 1;
else
return (n * Fact(n-1));
}
Output
Enter the number: 5
Factorial of 5 = 120
Post navigation

Tower of Hanoi
The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower,[1] and sometimes pluralized)
is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes
which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of
size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple
rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.

15
Queue
A Queue is a linear data structure in which deletions can only occur at one end, known as
the front, and insertions can only occur at the other end, known as the rear. It is similar to the
real-life queue where the first person entering the queue is the first person who comes out of the
queue. Thus queues are also called FIFO(First In First Out) lists.

Basic Operations of Queue


A queue allows the following basic operations:
• Enqueue – Add new element to the end of the queue.
• Dequeue – Remove an element from the front of the queue.
Every queue includes two pointers,
FRONT
and
REAR
, which indicate the position where deletion and insertion can be performed. Initially, values of
FRONT and REAR is set to -1.

Enqueue Operation
Inserting a new element in the position pointed by REAR is called the enqueue operation. We
must check if the queue is full before insertion. After the enqueue operation the REAR is
incremented by 1 and will point to the newly inserted element.
For inserting the first element in a queue, the value of FRONT has to be set to 0.
Consider a queue of size 5. Suppose we have to insert A, B, C, D and E into the queue. The
following changes will be made to the queue.

16
Enqueue Operation on a Queue

Dequeue Operation
Deleting an element in the position pointed by FRONT is called the dequeue operation. We must
check if the queue is empty before deletion. After the dequeue operation, the FRONT is
incremented by 1.
After deleting the last element in a queue, the value of FRONT and REAR has to be set to 0.
Consider the following example where we dequeue elements one by one until the queue becomes
empty.

Dequeue Operation on a Queue

17
Representation of Queues
Queue is usually represented in the computer using a linear array or a one-way linked list.
Array Representation of Queue
A queue can be represented in a program by using a linear array of elements and three pointer
variables FRONT, REAR and MAX.
The queue is empty if
FRONT = REAR = -1
.The queue is full if
FRONT =1
and
REAR = MAX - 1

Array Representation of a Queue

The size of the above queue is 5. It has 3 elements A, B and C. The FRONT, REAR and MAX
pointers will have values 0, 2 and 5 respectively.
The algorithms for enqueue and dequeue operations are given below.

Algorithm: ENQUEUE(QUEUE, MAX, FRONT, REAR, ITEM)


Step 1: IF REAR = MAX-1
Write OVERFLOW
Goto step 4
[END OF IF]
Step 2: IF FRONT=-1 and REAR=-1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = ITEM
Step 4: EXIT
Print overflow and exit if the queue is full.
For adding first element make
FRONT = 0
Increment REAR by 1.
Insert new element in the position pointed by REAR.

Algorithm DEQUEUE(QUEUE, MAX, FRONT, REAR, ITEM)


Step 1: IF FRONT = -1 OR FRONT > REAR
Write UNDERFLOW
ELSE
SET ITEM = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT
18
• Print underflow and exit if the queue is empty.
• Return the value pointed by FRONT.
• Increment FRONT by 1.
• Set
FRONT = REAR = -1
for the last element.

Linked Representation of Queues


The disadvantage of using an array to represent a queue is that the array must be specified to
have a fixed size. If the array size cannot be known ahead of time, then the linked representation
is used.
The HEAD pointer of the linked list is used as the FRONT. Also, use another pointer called
REAR to store the address of the last element of the queue.

Linked Representation of a Queue

The algorithms for enqueue and dequeue operations are given below.

Algorithm: LINK_ENQUEUE
Step 1: Allocate memory for the new node and name it as PTR
Step 2: SET PTR -> DATA = VAL
Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
Step 4: END

19
Inserting an element in a linked queue

Algorithm: LINK_DEQUEUE
Step 1: IF FRONT = NULL
Write Underflow
Go to Step 5
[END OF IF]
Step 2: SET PTR = FRONT
Step 3: SET FRONT = FRONT -> NEXT
Step 4: FREE PTR
Step 5: END

Disadvantage of Queue
Look at the following queue.

You cannot insert a new value now, because the queue is completely full. Consider the following
case: two consecutive deletions are made.

20
Even though there is enough space to hold a new element, the overflow condition still occurs
since the condition
REAR = MAX – 1
is still valid. This is a major drawback of a linear queue. A solution to this problem is to make
the queue circular.

Types of Queues
A queue data structure can be classified into the following types:
• Circular Queue.
• Priority Queue.
• Dequeue.
Application of Queue
• Manage resource sharing such as CPU scheduling, disk scheduling..etc
• When data is sent and received between two processes asynchronously.
• Hadling of inrepputs in real time.
• Call waiting systems in call centers.

Limitation of Linear Queue


Look at the following queue.

You cannot insert a new value now, because the queue is completely full. Consider the following
case: two consecutive deletions are made.

Even though there is enough space to hold a new element, the overflow condition still occurs
since the condition rear = MAX – 1 is still valid. This non-usable empty space is a major
drawback of a linear queue. A solution to this problem is to make the queue circular.

Circular Queue
A circular queue is a special type of queue where the last element is connected back to the
first element thus forming a circle. In the circular queue, the first index comes right after the
last index.

Circular queue representation


21
We start insertion from the beginning of the queue if we reach the end of the queue.

Circular Queue Operations


Every queue includes two pointers,
FRONT
and
REAR
, which indicate the position where deletion and insertion can be performed. Initially,
values of FRONT and REAR is set to -1.
The circular queue is full if any of the following condition is met,
• FRONT = 0 and REAR = Max – 1
• FRONT = REAR + 1

Enqueue Operation
Inserting a new element in the position pointed by REAR is called the enqueue operation.
• Print overflow and exit if the queue is full.
• For adding first element make
FRONT = 0
.
• Increment REAR by 1.
• Insert new element in the position pointed by REAR.
Algorithm: Enqueue
Step 1: IF FRONT = and Rear = MAX-1
Write OVERFLOW
Goto step 4
[End OF IF]
Step 2: IF FRONT=-1 and REAR=-1
SET FRONT = REAR = 0
ELSE IF REAR = MAX-1 and FRONT != 0
SET REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = ITEM
Step 4: EXIT

Dequeue Operation

Deleting an element in the position pointed by FRONT is called the dequeue operation. We must
check if the queue is empty before deletion.
• Print underflow and exit if the queue is empty.
• Return the value pointed by FRONT.
• Increment FRONT by 1 circularly.
• Set
FRONT = REAR = -1
for the last element.
22
Algorithm: Dequeue
Step 1: IF FRONT = -1
Write UNDERFLOW
Goto Step 4
[END of IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
Step 4: EXIT

Enqueue and dequeue operations on a circular queue is illustrated below.

Enqueue and Dequeue Operations on a Circular Queue

23
A priority queue is a collection of elements, in which each element has been assigned
a priority value. The order in which the elements will be processed is decided by the priority
of the element.
• An element with higher priority is processed first.
• If elements with the same priority occur, they are processed according to the order in
which they were added to the queue.
Usually, a lower priority number means higher priority.

Representation of Priority Queue


Priority queue can be represented using an array or a linked list.
Linked Representation of Priority Queue
When a priority queue is implemented with a linked list, each node will contain three parts:
• Data.
• The priority number of the element (PRN).
• The address of the next element.
Following is an example of a linked representation of a priority queue.

Linked Representation of Priority Queue

It has 4 elements A, B, C, D having priority 1, 2, 2 and 3 respectively. Here A will be


processed first since it has a higher priority. Elements B and C has the same priority and we
can say that B was inserted in the queue before C.
Inserting a new element in a linked priority queue
• Traverse the list until finding a node PTR with a lower priority than the new element.
• Insert new element in front of the node PTR.
Consider the following linked priority queue where we have to insert a new element S having
priority 4.

Inserting a New Element in a Linked Priority Queue

24
If an element with the same priority as the new element already exists, the new element is put
after that element.
Deleting an element from a linked priority queue
The first node in the list will be deleted, and its data will be processed first.
Array Representation of Priority Queue
Priority queues can be also implemented using arrays. For each priority number, a separate
circular queue is used. Each queue will have its own FRONT and REAR pointers.
Take a look at the two-dimensional representation of a priority queue given below.

Array Representation of Priority Queue

Kth row in matrix maintains the queue of elements with priority number k. FRONT[K] and
REAR[K] contain the FRONT and REAR elements of row K of the queue.

Inserting a new element in a priority queue using array


• Find the smallest K such that FRONT[K] ≠ NULL.
• Delete and process the FRONT element in row K of queue.

Deleting an element from a priority queue using array


• Insert ITEM as the REAR element in row M of queue.

25

You might also like