Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Chapter 3 Introduction to stack and queue

Show the memory representation of stack using array with the help of a diagram.
Consider stack contains five integer elements represented with an array A in which each
element occupy 2 bytes memory. Array starts with base address of 2000.

List any 4 applications of queue.


 In computer system to maintain waiting list for single shared resources such as printer,
disk, etc.
 It is used as buffers on MP3 players, iPod playlist, etc.
 Used for CPU scheduling in multiprogramming and time sharing systems.
 In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
 Handling of interrupts in real-time systems.
 Simulation

Differentiate between stack and queue.( Any two points)


Stack Queue
1. Stack is a data structure in which insertion 1. Queue is a data structure in which insertion
and deletion operations are performed at and deletion operations are performed at
same end. different ends.

2. In stack an element inserted last is deleted 2. In Queue an element inserted first is


first so it is called Last In First Out list. deleted first so it is called First In First Out
list.

3.In stack only one pointer is used called as 3.In Queue two pointers are used called as
stack top front and rear

1|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

4. Example: Stack of books 4. Example: Students standing in


a line at fees counter

5.Application: 5. Application:
 Recursion  In computer system for
 Polish notation organizing processes.
 In mobile device for sending
receiving messages.

Convert infix expression into prefix expression:


(A+B)*(C/G)+F

Scanned Element Stack Expression

F NA F

+ + F

) +) F

G +) GF

/ +)/ GF

C +)/ CGF

( + / CGF

* +* / CGF

2|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

) +*) / CGF

B +*) B/ CGF

+ +*)+ B/ CGF

A +*)+ AB/ CGF

( +* +AB/ CGF

NA +*+AB/ CGF

Prefix conversion = +*+AB/ CGF

Convert the following infix expression to its prefix form using stack
A + B – C * D/E + F

Scanned Element Stack Expression

F NA F

+ + F

E + EF

/ +/ EF

D +/ DEF

* +* /DEF

C +* C/DEF

- +- * C/DEF

B - B+* C/DEF

+ + - B+* C/DEF

A NA +A- B+* C/DEF

3|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

Convert following expression into postfix form. Give stepwise procedure.


A+B↑C*(D/E)-F/G.

Scanned Symbol Operation stack Postfix Expression

A NA A

+ + A

B + AB

↑ +↑ AB

C +↑ ABC

* +* ABC↑

( +*( ABC↑

D +*( ABC↑D

/ +*(/ ABC↑D

E +*(/ ABC↑DE

) +* ABC↑DE/

- - ABC↑DE/*+

F - ABC↑DE/*+F

/ -/ ABC↑DE/*+F

G -/ ABC↑DE/*+FG

NA ABC↑DE/*+FG/-

Postfix Expression: ABC↑DE/*+FG/-

4|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

Describe queue full and queue empty operation conditions on linear queue with
suitable diagrams.
Queue full:-A queue is full when its rear pointer points to max -1 position. Max is
maximum number of elements in a queue. If rear pointer is not equal to max-1 then a new
element can be added to a queue. If queue is full then new element cannot be added to a
queue.
Example:-
Consider max=4. First element is stored at 0th position and last element is stored at 3 rd
position in queue. In the diagram given below rear pointer is pointing to max-1 (3) position
so queue is full.

Queue empty: A queue is empty when its front pointer points to -1 position. When front
pointer is -1 then one cannot delete any data from a queue.
Example:-In the diagram given below front pointer points to -1 value i.e. it points no
location inside queue so queue is empty.

Draw and explain construction of circular queue.


A queue, in which the last node is connected back to the first node to form a cycle, is called
as circular queue.

5|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

The above diagram represents a circular queue using array.


It has rear pointer to insert an element and front pointer to delete an element. It works in
FIFO manner where first inserted element is deleted first.
Initially front and rear both are initialized to -1 to represent queue empty. First element
inserted in circular queue is stored at 0th index position pointed by rear pointer. For the
very first element, front pointer is also set to 0th position.
Whenever a new element is inserted in a queue rear pointer is incremented by one. If rear
is pointing to max-1 and no element is present at 0th position then rear is set to 0 th position
to continue cycle.
Before inserting an element, queue full condition is checked. If rear is set to max-1 position
and front is set to 0 then queue is full. Otherwise if rear =front+1 then also queue is full.

If queue is full then new element cannot be added in a queue. For deletion, front pointer
position is checked and queue empty condition is checked. If front pointer is pointing to -1
then queue is empty and deletion operation cannot be performed. If queue contains any
element then front pointer is incremented by one to remove an element.

If front pointer is pointing to max-1 and element is present at 0th position then front
pointer is initialize to 0th position to continue cycle.
Circular queue has advantage of utilization of space. Circular queue is full only when there
is no empty position in a queue. Before inserting an element in circular queue front and
rear both the pointers are checked.
So if it indicates any empty space anywhere in a queue then insertion takes place.

Write a program in ‘C’ to insert an element in a linear queue.


C program to insert an element in a linear queue using array
#include<stdio.h>
#include<conio.h>
#define n 5
void main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
//clrscr();
printf("Queue using Array");

6|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

printf("\n1.Insertion \n2.Display \n3.Exit");


while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
printf("\n Queue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case 3:
exit(0);

7|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

default:
printf("Wrong Choice: please see the options");
}
}
}
getch();
}

Write algorithm for performing push and pop operations on stack.


Push algorithm: - Max is maximum size of stack.
Step 1: [Check for stack full/ overflow]
If stack_top is equal to max-1 then
Display output as “Stack Overflow” and return to calling function
Otherwise
Go to step 2
Step 2: [Increment stack_top] Increment stack top pointer by one.
stack_top=stack_top +1;
Step 3: [Insert element] stack [stack_top] = item;
Step 4: return to calling function

Pop algorithm: - Max is maximum size of stack.


Step 1: [Check for stack empty/underflow]
If stack_top is equal to -1 then
Display output as “Stack Underflow” and return to calling function
Otherwise
Go to step 2
Step 2: [delete element] stack [stack_top] = item;
Step 3: [Decrement stack_top] Decrement stack top pointer by one.
stack_top=stack_top -1;
Step 4: return to calling function.
8|Page Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

Define the term recursion. Write a program in C to display factorial of an entered


number using recursion.
Definition: Recursion is the process of calling function by itself. A recursive function body
contains function call statement that calls itself repeatedly.
Program:
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int n;
clrscr();
printf("\nThe factorial of % is = %d",n,fact(n));
getch();
}
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}

Evaluate the following postfix expression:


5, 6, 2, +, *, 12, 4, /, - Show diagrammatically each step of evolution using stack.

9|Page Mr.KAZI A S M-9765645688


Chapter 3 Introduction to stack and queue

5
6

5
6
2

11 6+5
2

22 2*11

12
22

4
12
22

3 12/4
22

19 22-3

Evaluate the following prefix expression:


- * + 4 3 2 5 show diagrammatically each step of evaluation using stack.
5

2
5

3
2
5

4
3
2
5

7 4+3
2

10 | P a g e Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

14 7*2
5

9 14-5

Show the effect of PUSH and POP operation on to the stack of size 10. The stack
contains 40, 30, 52, 86, 39, 45, 50 with 50 being at top of the stack. Show
diagrammatically the effect of:
(i) PUSH 59 (ii) PUSH 85
(iii) POP (iv) POP
(v) PUSH 59 (vi) POP
Sketch the final structure of stack after performing the above said operations.

Evaluate the following postfix expression:


57+62-*
11 | P a g e Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

7
5

12 5+7

12
6

12
6 6-2
2

12
4

48 12*4

Linear queue
1. A linear queue can be found in a time-sharing computer system where many users
share the system simultaneously.
2. The first element, which is added into the queue will be the first one to be removed.
Thus queues are also called First-in First-Out lists (FIFO) or Last-In-Last-Out lists
(LILO).

 Queues may be represented in the computer memory by means of linear arrays or


linked list.
 There are two pointer variables namely FRONT and REAR.
 The FRONT denotes the location of the first element of the queue.
 The rear describes the location of the rear element of the queue.
 When the queue is empty, the values of front and rear are-1 and -1 respectively.

12 | P a g e Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

 The “max size “represent the maximum capacity of the linear queue.
 The following is the condition to test the queue is full or not. (Rear== max size-1)
 To insert the first element both pointers should be altered to ‘0’ Front =0 rear=0.
 Whenever an item is added to the queue, the value of REAR is incremented by 1.
REAR =REAR+1;
 The following is the condition to test the queue is empty or not. Front==-1
 Whenever an “Item” is deleted from the queue, the value if front is incremented by 1
Front=Front+1;
 To delete the last element, both pointers should be altered.
 Front=-1; Rear=-1;

Applications of Queue:
Queue is used when things don’t have to be processed immediatly, but have to be
processed in First InFirst Out order
1) When a resource is shared among multiple consumers. Examples include CPU
scheduling, Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as
sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.

Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it, and then
completely erasing it from the memory. Here we shall try to understand the basic
operations associated with queues −
 enqueue() − add (store) an item to the queue.
 dequeue() − remove (access) an item from the queue.
Few more functions are required to make the above-mentioned queue operation efficient.
These are −
 peek() − Gets the element at the front of the queue without removing it.
 isfull() − Checks if the queue is full.
 isempty() − Checks if the queue is empty.

Enqueue Operation

13 | P a g e Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

Queues maintain two data pointers, front and rear. Therefore, its operations are


comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
 Step 1 − Check if the queue is full.
 Step 2 − If the queue is full, produce overflow error and exit.
 Step 3 − If the queue is not full, increment rear pointer to point the next empty
space.
 Step 4 − Add data element to the queue location, where the rear is pointing.
 Step 5 − return success.

 
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is
pointing and remove the data after access. The following steps are taken to
perform dequeue operation −
 Step 1 − Check if the queue is empty.
 Step 2 − If the queue is empty, produce underflow error and exit.
 Step 3 − If the queue is not empty, access the data where front is pointing.
 Step 4 − Increment front pointer to point to the next available data element.
 Step 5 − Return success.

14 | P a g e Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

What is Circular Queue?


A Circular Queue can be defined as follows...
A circular queue is a linear data structure in which the operations are performed based on
FIFO (First In First Out) principle and the last position is connected back to the first
position to make a circle.

Graphical representation of a circular queue is as follows...

Implementation of Circular Queue

15 | P a g e Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

To implement a circular queue data structure using an array, we first perform the following
steps before we implement actual operations.
 Step 1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
 Step 2 - Declare all user defined functions used in circular queue implementation.
 Step 3 - Create a one dimensional array with above defined SIZE (int cQueue[SIZE])
 Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'.
(int front = -1, rear = -1)
 Step 5 - Implement main method by displaying menu of operations list and make
suitable function calls to perform operation selected by the user on circular queue.

Difference between Linear Queue and Circular Queue

BASIS FOR
LINEAR QUEUE CIRCULAR QUEUE
COMPARISON

Basic Organizes the data elements and Arranges the data in the circular
instructions in a sequential order pattern where the last element is
one after the other. connected to the first element.

Order of task Tasks are executed in order they Order of executing a task may
execution were placed before (FIFO). change.

Insertion and The new element is added from Insertion and deletion can be done
deletion the rear end and removed from at any position.
the front.

Performance Inefficient Works better than the linear queue.

Priority queue

16 | P a g e Mr.KAZI A S M-9765645688
Chapter 3 Introduction to stack and queue

A priority queue is a collection in which items can be added at any time, but the only item
that can be removed is the one with the highest priority.
Operations
add(x): add item x
remove: remove the highest priority item
peek: return the highest priority item (without removing it)
size: return the number of items in the priority queue
isEmpty: return whether the priority queue has no items
Examples
Patients in an emergency room
Operating system scheduler
Routing
A* search
Simulation
Many more examples

17 | P a g e Mr.KAZI A S M-9765645688

You might also like