0% found this document useful (0 votes)
11 views67 pages

3 Stack and Queue

Uploaded by

Shrawani Dongre
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)
11 views67 pages

3 Stack and Queue

Uploaded by

Shrawani Dongre
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/ 67

PIMPRI CHINCHWAD EDUCATION TRUST’S

PIMPRI CHINCHWAD POLYTECHNIC

NBA Accredited Institute


I.S.O. Certified Organization, Approved by A.I.C.T.E.
Affiliated to M.S.B.T.E. Mumbai

Address : Pimpri Chinchwad Polytechnic


Sector No. 26, Pradhikaran, Nigdi,
Pune - 411 044
Phone: 020 - 2765 4156 / 2765 8797
Fax: 27654156
Email: [email protected]
Website: www.pcpolytechnic.com
Pimpri Chinchwad Education Trust’s

Pimpri Chinchwad Polytechnic


Sector No. 26, Pradhikaran, Nigdi, Pune – 411044
(NBA Accredited / An ISO 9001:2015 Certified)
Phone: 020-27654156 / 27658797 Fax: 27654156
Website : www.pcpolytechnic.com Email:
[email protected]

Department : Computer Engineering


Course : Data Structures Using ‘C’
Course Code : 22317

Course Outcomes (COs) :


a. Perform basic operations on arrays
b. Apply different searching and sorting techniques.
c. Implement basic operations on stack and queue using array
representation.
d. Implement basic operations on Linked List.
e. Implement program to create and traverse tree to solve problems.

Pimpri Chinchwad Polytechnic, Computer Department


Course : Data Structures Using ‘C’
Course Code : 22317

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Suggested Learning Resources :

Balgurusamy, E.
01 Data Structures using ‘C’

● McGraw Hill Education, New Delhi

ISRD Group
02 Data Structures using ‘C’

● McGraw Hill Education, New Delhi

03 Data Structures with ‘C’ (SIE)


(Schaum’s Outline Series)


Lipschutz
McGraw Hill Education, New Delhi

Steve Qualline
04 Practical ‘C’ Programming

● O’Reilly Media

05 Data Structures


Dr. Rajendra Kawale
Devraj Publicatiions

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Suggested Learning Websites:

❏ http://nptel.ac.in/courses/106102064/1
❏ www.oopweb.com/algorithms
❏ www.studytonight.com/data-structures/
❏ www.cs.utexas.edu/users
❏ liscs.wssu.edu
❏ http://www.academictutorials.com/data-structure/
❏ http://www.sitesbay.com/data-structure/c-data-structure
❏ http://www.indiabix.com
❏ http://www.khanacademy.org/

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Unit : III
Stacks and Queues

3.1 Introduction to Stack 3.2 Introduction to Queue:

- Stack representation in memory using array - Queue representation in memory using array

- Stack as an ADT - Queue as an ADT

- Stack Operations – PUSH, POP - Types of Queues :- Linear Queue, Circular

- Stack Operations Conditions – Stack Full / Stack Queue, Concept of Priority Queue

Overflow, Stack Empty / Stack Underflow. - Queue Operations – INSERT, DELETE

- Applications of Stack - Queue Operations Conditions – Queue Full,

· Reversing a list, Polish notations, Conversion of Queue Empty

infix to postfix expression, Evaluation of - Applications of Queue

postfix expression, Converting an infix into


prefix expression, Evaluation of prefix
expression , Recursion, Tower of Hanoi

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
Stack is LIFO (Last In First Out) or FILO (First In Operations performed on the stack :
Last Out) data structure. A stack is a linear data PUSH( ), POP( ), init( ), isFull( ), isEmpty( ), peek( )
structure in which data is added or removed from
one end called as ‘top’ of the stack. PUSH( ) : It is used to add/insert/push an element
onto the stack.
Formally, stack may be defined as follows :
typedef struct stack POP( ) : It is used to delete/remove/pop an element
{ from the stack.
int a[max];
init( ) : It is used to initialize the stack using top = -1
int top;
}stack; isFull( ) : Used to check whether stack is full or not. It
- where ‘a’ is the array where ‘max’ number of returns true if stack is full otherwise returns false.
elements can be stored and ‘top’ is a variable from
isEmpty( ) : Used to check whether stack is empty or
where data can be added onto the stack or data can
be removed from the stack. not. It returns true if stack is empty otherwise returns
Stack can be implemented using array or linked list. false.
peek( ) : Used to get the value indicated by ‘top’
without modifying the stack.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack : - top = -1 is a stack empty condition. The POP()
operation will delete / remove / pop the element
Stack representation in memory using array : a indicated by ‘top’ and then ‘top’ will be decremented
- Stack can be represented in memory using array to by one. If top = -1 which is stack empty condition and
contain ‘max’ elements. it indicates that pop operation is not possible as there
- A variable ‘top’ contains the location or position of is no single element in the stack.
the top element in the stack. Stack underflow means trying to delete / remove / pop
- A variable ‘max’ gives the maximum number of an element from the stack which is already empty.
elements the stack can store.
- Initially , top is set to -1. max = 5
4
- top = max - 1 is a stack full condition. 4 50 top
In the PUSH() operation, top will be incremented by
3
one and at that location a new element is inserted 3 40
into the stack. 2
If the value of the ‘top’ reaches to ‘max-1’ , which is 2 30
stack full condition and it indicates that no more 1
elements can be inserted into the stack. 1 20
Stack overflow means trying to add / insert / push 0
0 10
an element into the the stack which is already full.
-1
Stack Full / overflow Stack Empty / underflow
top

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Array and Stack :

Stack :
Array :
1. A new element can be added only at the top of
1. We can insert element at any location in array.
the stack.
2. Any element of the array can be accessed.
3. An array is static data structure i.e. its size 2. Only the topmost element can be accessed.
3. A stack is a dynamic data structure i.e. its size
remains constant.
increases or decreases as elements are inserted or
4. There is an upper limit on the size of the array
deleted.
which is specified during declaration.
4. Logically, stack can grow to any size.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
Algorithm for PUSH( ) operation of Stack : Algorithm for POP( ) operation of Stack :
Step 1 : [Check whether stack is full] Step 1 : [Check whether stack is empty]
a. if top==max-1 then a. if top==-1 then
print : stack is full print : stack is empty
return return
b. else b. else
set top=top+1 [increment top by 1] set data = stack[top] [Delete Data from top of
set stack[top] = data [Insert Data at top in stack]
stack] set top=top-1 [decrement top by 1]
Step 2 : Return / End Step 2 : Return / End

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
do
Stack : {
//Program to implement the Stack printf("\n-------------MENU----------------\n");
printf("\t 1.Push \t 2.Pop \t 3.Display \t 4.Exit");
#include<stdio.h> printf("\n--------------------------------------\n");
#include<conio.h> printf("\n\t Enter your choice=");
scanf("%d",&ch);
#define max 5 switch(ch)
//------------Functions & Variable declaration------- {
case 1: push();
int a[max],top=-1; break;
void push(void); case 2: pop();
break;
void pop(void); case 3: display();
void display(void); break;
case 4: exit();
//--------------Main Program----------------------- break;
void main() default:
printf("\n\t Invalid choice");
{ }
int ch; }while(ch!=4);
getch();
clrscr(); }

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//-------------------------INSERT----------------------- //-----------------DELETE-----------------------
void push() void pop()
{ {
int val; int val;
if(top==max-1) if(top==-1)
//STACK-FULL CONDITION //STACK-EMPTY CONDITION
{ {
printf("\n\t Stack Full.."); printf("\n\t Stack Empty..");
} }
else else
{ {
top++; val=a[top];
printf("\n\t Enter Value="); top--;
scanf("%d",&val); printf("\n\t Deleted value=%d",val);
a[top]=val; display();
display(); }
} }
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//-------------------------DISPLAY----------------------
-
void display()
{
int i;
printf("\n\t Current status of stack:");
if(top==-1)
//STACK-EMPTY CONDITION
{
printf("\n\t Stack Empty..");
}
else
{
for(i=0;i<=top;i++)
{
printf(" %d ",a[i]);
}
}
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :

Applications of Stack :
❏ Stack machine

❏ Recursion ❏ Matching parenthesis in an expression

❏ Expression conversion & evaluation: Polish ❏ Tower of Hanoi

Notation ❏ Reversing List

[Conversion from infix to postfix expression, ❏ Interrupt handling

Evaluation of Postfix expression,


Conversion from infix to prefix expression,
Evaluation of Prefix expression,
Evaluation of arithmetic expression]

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack : for(i=0;i<max;i++)
//Program to reverse a list : {
#include<stdio.h> val = a[top];
#include<conio.h> top--;
#define max 5 b[i]=val;
int a[max],b[max],top=-1; }
//--------------Main Program----------------------- printf("\n\t Elements of Stack a are : ");
void main() for(i=0;i<max;i++)
{ {
int i,val; printf("\n\t a[%d] : %d",i,a[i]);
printf("\n\t Enter %d elements for stack a : ",max); }
clrscr(); printf("\n\t Elements of Stack b are : ");
for(i=0;i<max;i++) for(i=0;i<max;i++)
{ {
printf("\n\t a[%d] : ",i); printf("\n\t b[%d] : %d",i,b[i]);
scanf("%d",&val); }
top++; getch();
a[top]=val; }
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Polish Notations : are as follows
Infix Expression ( a + b)
Prefix Expression ( + a b)
Postfix Expression ( a b +)

Infix Expression :-
It contains the operator in-between the operands. Format : {operand operator operand} Ex.: a + b

Prefix Expression :-
It contains the operator before the operands. Format : {operator operands} Ex.: + ab

Postfix Expression :-
It contains the operator after the operands. Format : {operands operator} Ex.: ab +

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Postfix (Manual
method) :
While evaluating an infix expression, there is an
evaluation order according to which the operations
are executed:
❏ Brackets or parentheses
❏ Exponentiation
❏ Multiplication / Division / Modulus
❏ Addition / Subtraction
The operators with same priority (eg. * & / ) are
evaluated from left to right.
The steps to convert infix to postfix are as follows:
i. The actual evaluation is determined by inserting
brackets.
ii. Convert the expression in the innermost
brackets into postfix notation by putting the
operator after the operands.
iii. Repeat above step ii until the entire expression
is converted into postfix notation.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Postfix (Manual
method) :

source of images :https://www.ritambhara.in/infix-prefix-postfix-notations-polish-notations/


http://www.andrew.cmu.edu/course/15-111-kesden/su05/applications/ln/lecture9.older.html

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Postfix (Manual //Conversion from Infix to Postfix (Manual
method) : method) :
EX.1: A + B * C EX.3: [[(A + B) / (C + D)] - (D * E)]
=> [A + (B*C)] => [[(AB+) / (CD+)] - (DE*)]
=> [A + BC*] => [[AB+ CD+ /] - DE*]
=> ABC*+ => AB+ CD+ / DE* -

EX.2 : ( A-B) * (C+D)


=> (AB- * CD+)
=> (AB- CD+ *)
=> AB- CD+ *

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Postfix (Manual method) :

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Prefix (Manual
method) :
While evaluating an infix expression, there is an
evaluation order according to which the operations
are executed:
❏ Brackets or parentheses
❏ Exponentiation
❏ Multiplication / Division / Modulus
❏ Addition / Subtraction
The operators with same priority (eg. * & / ) are
evaluated from left to right.
The steps to convert infix to prefix are as follows:
i. The actual evaluation is determined by inserting
brackets.
ii. Convert the expression in the innermost
brackets into prefix notation by putting the
operator before the operands.
iii. Repeat above step ii until the entire expression
is converted into prefix notation.

source of images :https://www.slideserve.com/yuri-santana/data-structures https://squeaksvideo.com/watch/prefix-to-infix-test_CM9j48hrsLlXbhI.html

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Prefix (Manual
method) :

source of images :https://www.ritambhara.in/infix-prefix-postfix-notations-polish-notations/


http://www.andrew.cmu.edu/course/15-111-kesden/su05/applications/ln/lecture9.older.html

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Prefix (Manual //Conversion from Infix to Prefix (Manual
method) : method) :
EX.1: A + B * C EX.3: [[(A + B) / (C + D)] - (D * E)]
=> [A + (B*C)] => [[(+AB) / (+CD)] - (*DE)]
=> [A + *BC] => [[/ +AB +CD] - *DE]
=> +A*BC => - / +AB +CD *DE

EX.2 : ( A-B) * (C+D)


=> (-AB * +CD)
=> (* -AB +CD )
=> * -AB +CD

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Prefix (Manual method) :

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//ALGORITHM OF - Conversion from Infix to Postfix using stack :

STEP 1: Enclose the entire infix expression within left parenthesis “(“ and “)” right parenthesis.
STEP 2: Read the infix expression from left to right and repeat the steps 3 to 6 for each element of infix
expression until the stack is empty.
STEP 3: If an operand is there then add it to postfix expression.
STEP 4: If left parenthesis “(“ is there then push it onto the stack.
STEP 5: If an operator is there then -
a) If the operator on the stack has the same or higher precedence than this operator (the operator from infix
expression) then repeatedly pop the operators from stack and add to postfix expression.
b) Add this operator (the operator from infix expression) to the stack.
STEP 6: If right parenthesis “)” is there then
a) Repeatedly pop each operator from top of the stack and add to postfix expression until a left parenthesis
“(“ is there.
b) Remove left parenthesis “(“ from the infix expression.
STEP 7: Exit

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Postfix using stack :
Ex.1: A + B * C
Step 1: “(“ to stack and “)” at the end of expression
=> A + B *C)
Infix Stack Postfix expression
Infix Stack Postfix expression

( C * ABC
+
A ( A (

+ + A ) ABC*+
(

B + AB
(
Final answer : ABC*+
* * AB
+
(

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Postfix using stack :
Ex.1: A * B + C
Step 1: “(“ to stack and “)” at the end of expression
=> A * B +C )
Infix Stack Postfix expression
Infix Stack Postfix expression

( C + AB*C
(
A ( A
) AB*C+
* * A
(

B * AB
(
Final answer : AB*C+
+ + AB*
(

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack : Infix Stack Postfix expression
//Conversion from Infix to Postfix using stack :
Ex.1: ((A +B)* D)^(E-F) Infix Stack Postfix expression ( ( AB+D*
Step 1: “(“ to stack and “)” at the end of expression
=> ((A +B)* D)^(E-F)) ^
Inf Sta Postfix
B + AB (
ix ck expression (
( E ( AB+D*E
( ( ^
(
( ( ) ( AB+
( ( - - AB+D*E
(
( ( * * AB+ ^
( ( (
( (
F - AB+D*EF
A ( A D * AB+D (
( ( ^
( ( (

+ + A ) ( AB+D* ) ^ AB+D*EF-
( (
( ^ ^ AB+D*
Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
( ( ) AB+D*EF-^
//Conversion from Infix to PREfix using stack :
Infi Stac PREfix
Infi Stac PREfix
Ex.1: ((A +B)* D)^(E-F) x k expression
x k expression
Step 1: “)“ to stack and “(” at START of expression
=> (((A +B)* D)^(E-F) Infix Stack PREfix expression
* * FE-D + + FE-DB
E - FE ) )
*
Infix Stack PREfix expression) ^
) ) )
^
)
( ) FE- ) ) FE-D )
) ) *
^ ^ FE- ) A + FE-DBA
)
) ^ )
F ) F ) *
) ) ) FE- )
^ B ) FE-DB ^
- - F ) * )
) )
) D ) FE-D ^ ((( FE-DBA+*^
^ )
) ^*+ABD-EF

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//ALGORITHM OF - Conversion from Infix to Prefix using stack :

STEP 1: STEP 1: Enclose the entire infix expression within left parenthesis “(“ and “)” right parenthesis.
STEP 2: Read the infix expression from right to left and repeat the steps 3 to 6 for each element of infix
expression until the stack is empty.
STEP 3: If an operand is there then add it to prefix expression.
STEP 4: If right parenthesis “)“ is there then push it onto the stack.
STEP 5: If an operator is there then -
a) If the operator on the stack has the same or higher precedence than this operator (the operator from infix
expression) then repeatedly pop the operators from stack and add to prefix expression.
b) Add this operator (the operator from infix expression) to the stack.
STEP 6: If left parenthesis “(” is there then
a) Repeatedly pop each operator from top of the stack and add to prefix expression until a right parenthesis
“)“ is there.
b) Remove right parenthesis “)“ from the infix expression.
STEP 7: Reverse the output from the prefix expression to display the result.
STEP 8: Exit

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Prefix using stack :
Ex.1: A + B * C
Step 1: “)“ to stack and “(” at the start of expression
=> (A + B * C and read from right to left
Infix Stack Prefix expression
Infix Stack Prefix expression

) A + CB*A
)
C ) C
( CB*A+
* * C
) (now reverse this
expression for result)
B * CB
)
Final answer : +A*BC
+ + CB*
)

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//Conversion from Infix to Prefix using stack :
Ex.1: A * B + C
Step 1: “)“ to stack and “(” at the start of expression
=> (A * B + C and read from right to left
Infix Stack Prefix expression
Infix Stack Prefix expression

) A * CBA
+
C ) C )

+ + C ( CBA*+
)
(now reverse this
B + CB expression for result)
)

* * CB Final answer : +*ABC


+
)

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//ALGORITHM OF - Evaluation of Postfix expression using stack :
[Read the expression from left to right]
STEP 1: Read the element.
STEP 2: If the element is an operand then push it onto the stack.
STEP 3: If the element is an operator then
i. Pop 2 operands from the stack as A(first popped operand) and B(second popped
operand).
ii. Evaluate B operator A.
iii. Push the result of B operator A onto the stack.
STEP 4: If no more elements then
POP the result
else goto Step 1.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack : //Evaluation of Postfix using stack :
Infix Stack Operations
Ex.1: 6 5 3 + 9 * + Element
=> Read from left to right
9 9
Infix Stack Operations 8
Element 6

6 6 * 72 Pop topmost 2 elements from


6 stack : A=9, B=8
5 5 Evaluate B op A = 8*9=72
6 Push result (72) on stack
3 3 + 78 Pop topmost 2 elements from
5 stack : A=72, B=6
6 Evaluate B op A = 72+6=78
Push result (78) on stack
+ 8 Pop topmost 2 elements
6 from stack : A=3, B=5 Since no more elements in
Evaluate B op A = 5+3=8 postfix expression pop result(78)
Push result (8) on stack from stack as final answer
Final answer : 78

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack :
//ALGORITHM OF - Evaluation of Prefix expression using stack :
[Read the expression from right to left]
STEP 1: Read the element.
STEP 2: If the element is an operand then push it onto the stack.
STEP 3: If the element is an operator then
i. Pop 2 operands from the stack as A(first popped operand) and B(second popped
operand).
ii. Evaluate A operator B.
iii. Push the result of A operator B onto the stack.
STEP 4: If no more elements then
POP the result
else goto Step 1.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack : //Evaluation of Prefix using stack :
Ex.1: + 5 * 3 2
=> Read from right to left Infix Stack Operations
Element

Infix Stack Operations 5 5


Element 6

2 2 + 11 Pop topmost 2 elements


from stack :A=5, B=6
3 3 Evaluate A op B =
2 5+6=11
Push result(11) on stack
* Pop topmost 2 elements
6 from stack :A=3, B=2 Since no more elements
Evaluate A op B = 3*2=6 in prefix expression pop
Push result(6) on stack result(11) from stack as
final answer

Final answer : 11

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :
Queue is FIFO (First In First Out) or LILO (Last In Operations performed on the queue :
Last Out) data structure. A queue is a linear data INSERT( ), DELETE( ), init( ), isFull( ), isEmpty( )
structure in which data can be deleted only from
one end called as ‘front’ and data can be inserted INSERT( ) : It is used to add/insert an element into
from other end called as ‘rear’ .
the queue.
Formally, queue may be defined as follows : DELETE( ) : It is used to delete/remove an element
typedef struct queue from the queue.
{
init( ) : It is used to initialize the queue using front =
int a[max];
int front, rear; -1 and rear = -1.
}queue; isFull( ) : Used to check whether queue is full or not.
- where ‘a’ is the array where ‘max’ number of
It returns true if queue is full otherwise returns false.
elements can be stored, ‘front’ is a variable from
where data can be deleted and ‘rear’ is variable from isEmpty( ) : Used to check whether queue is empty
where data can be added into the queue. or not. It returns true if queue is empty otherwise
Queue can be implemented using array or linked list.
returns false.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue : - (front= -1 AND rear= -1)
is a queue empty condition.
Queue representation in memory using array :
-1 0 1 2 3 4
- Queue can be represented in memory using array
Queue
to contain ‘max’ elements. Empty
- ‘front’ is a variable from where data can be deleted
front , rear
and ‘rear’ is variable from where data can be added
into the queue.
- A variable ‘max’ gives the maximum number of
elements the queue can store. max = 5
- (rear = max - 1) is a queue full condition.
- Initially , front and rear are set to -1.
max = 5
0 1 2 3 4
Queue 10 20 30 40 50
Full
front rear

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue : So to add 40 in this queue:
INSERT() operation of Queue : rear++;
queue[rear]=40;
- In the INSERT() operation, rear will be incremented
by one and at that location a new element is inserted After adding 40, queue is:
into the queue.
For. Ex.
0 1 2 3 4
max = 5
Initially queue is:
10 20 30 40

front rear
0 1 2 3 4

10 20 30
If the value of the ‘rear’ reaches to ‘max-1’ , which is
queue full condition and it indicates that no more
front rear
elements can be inserted into the queue.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :
DELETE() operation of Queue :

After deleting the element, queue is:


- The DELETE() operation will delete / remove the
element indicated by ‘front’ and then ‘front’ will be
incremented by one.
For. Ex.
0 1 2 3 4
max = 5
Initially queue is:
20 30 40

front rear
0 1 2 3 4

10 20 30 40
If (front= -1 AND rear= -1) which is queue empty
condition and it indicates that DELETE operation is
front rear
not possible as there is no single element in the
queue.
Delete the element indicated by ‘front’ and then
increment ‘front’ by 1 (front++;).

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Insert
Queue : (10)
-1 0 1 2 3 4

Algorithm for INSERT( ) operation of Queue : 10


Step 1 : [Check whether queue is full]
a. if rear==max-1 then front , rear
print : queue is full Insert -1 0 1 2 3 4
(20)
return
10 20
b. else
if(front= = -1) then front rear
set front=front+1 [set front = 0]
set rear=rear+1 [set rear = 0] Insert -1 0 1 2 3 4
(30)
else
10 20 30
rear++ [Increment rear by 1]
[end of if] front rear
set queue[rear] = data [Insert Data indicated
by rear in queue] Insert -1 0 1 2 3 4
(40)
[end of if]
10 20 30 40
Step 2 : Return / End
For Ex. : front rear
Initially -1 0 1 2 3 4 Insert -1 0 1 2 3 4
queue is (50)
empty 10 20 30 40 50 Queue
Full
front , rear front rear

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
delete() :
Queue : -1 0 1 2 3 4

Algorithm for DELETE( ) operation of Queue : 10 20 30


Step 1 : [Check whether queue is empty]
a. if (front == -1 AND rear==-1) then front rear
print : queue is empty delete() : -1 0 1 2 3 4
return
b. else 10 20 30
set data = queue[front] [Delete Data indicated by
front from queue] front, rear
set front=front+1 [increment front by 1] delete() : -1 0 1 2 3 4
display the value ‘data’ deleted from the queue
if(front > rear) then 10 20 30
set front = rear = -1 [queue empty condition]
[end of if] rear front
[end of if] Since -1 0 1 2 3 4
Step 2 : Return / End (front > rear)
For Ex. : =>
Initially -1 0 1 2 3 4 front=rear=-1
queue
front , rear
is : 10 20 30

front rear Now Queue is Empty

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
switch(ch)
Queue :
{
#include<stdio.h> case 1: insert( );
#include<conio.h> break;
#define max 5 case 2: delete1();

void insert(); break;


void delete1(); case 3: display();
void display(); break;
case 4: exit(0);
int q[max],front=-1,rear=-1; default: printf("\n\t Invalid
void main() Choice");
{ }
int ch; }while(ch!=4);
clrscr(); getch();
do }
{
printf("\n\t -------------------------MENU-------------------------");
printf("\n\t 1.Insert \t 2.Delete \t 3.Display \t 4.Exit");
printf("\n\t -------------------------------------------------
-----");
printf("\n\t Enter your choice=");
scanf("%d",&ch);

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
//-------------DELETE ELEMENT-----------------
Queue :
void delete1()
//------------------INSERT ELEMENT-------------------------- {
void insert() int val;
{ if(front==-1 && rear==-1)
int val; {
if(rear==max-1) printf(“\n\tQueue is empty...”);
{ printf("\n\t Queue Full!!"); } }
else else
{ {
printf("\n\t Enter Data="); val=q[front];
scanf("%d",&val); front++;
if(front= = -1 && rear = = -1)
{ front=0; printf("\n\t Deleted Value=%d",val);
rear=0; display( );
} if(front > rear)
else {
{ rear++; } front=-1;
q[rear]=val; rear=-1;
}
display(); }
} }
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :
//---------------------DISPLAY------------------------------------------
void display()
{
int i;
if(front==-1 && rear==-1)
{
printf("\n\t Queue Empty..");
}
else
{
for(i=front;i<=rear;i++)
{
printf("\n\t %d",q[i]);
}
}
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :
STACK QUEUE
1) Stack is a [FILO] or [LIFO] data structure 1) Queue is [FIFO] or [LILO] data
structure.
2) In stack there is only one end through which data can be inserted 2) There are two ends in queue, the data is
or deleted from the stack which is called as ‘top’. deleted from ‘front’ end and data
is inserted
from ‘rear’ end.
3) There are two basic operation performed on stack: 3) There are two basic operation perform on queue:
a) PUSH b) POP a) INSERT (enqueue) b)
DELETE (dequeue)
4) stack is used in recursion. 4) Queue is used for
process scheduling
5) data structure of stack:- 5) data structure of
queue:-
typedef struct stack typedef struct queue
{ {
int a[max]; int
a[max];
int top; int
front,rear;
} stack; } queue ;
6) "TOP" moves in both directions. 6) "FRONT" and "REAR" move in
one direction.
Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
7) In stack the elements are removed in the reverse order 7) In queue the elements are removed in the
Queue :
Applications of Queue :

* Types of queues:- 1) operating system often maintains a queue of processes that are ready
· linear queue to execute or that are waiting for a particular event to occur.

· circular queue 2) computer system must often provide an "BUFFER AREA" for the
· priority queue messages sent between two processes, two programs or even two
systems.This buffer are is implemented as a queue.
· double ended queue
3) Queues are used to queue-up the print jobs which is normally known as
"Spooling".

4) Queue is also used for scheduling of jobs.(using round robin algorithm).

5) Queues are used in railway reservation applications.

6) Queues are used in online transaction operation in banking.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

Priority Queue
A priority queue is an ADT in which each element is assigned the priority.
An element with higher priority is processed before an element with a lower priority.
Two element with same priority are processed on first come first serve basis.
The priority queue of the element can be based on various factors.
For example – If there are three processes First process Needs 5 nano second to complete, second
process Needs 4 nano second to complete and third process needs 6 nano seconds .
Then the second process will have the highest priority & will thus be the first to be executed .
There are two types of Priority Queue’s as follows:
1. Ascending priority queue.
2. Descending priority queue.
1. Ascending priority queue :
In this queue element can be inserted randomly but only the smallest element can be removed
first.
2. Descending priority queue :
In this queue element can be inserted randomly but only the largest element can be removed first.
In both the above types if elements with equal priority are present then First In First Out ( FIFO ) is applied.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

· Applications of Priority Queue :

1. A priority queue is used in computer network and devices like routers for efficient routing of packet of over
a network . Packets that contain important data or the data that must arrive on time would be given higher
priority and would therefore the transmitted ahead of lower priority data.

2. In an operating system a priority might handled the jobs i.e. programmes waiting for execution . When
processing time becomes available high priority job would be removed from the priority queue for the
processing.

3. It is useful for categorising the data.

4. It is mostly used in simulators.


•Advantages of Priority Queue:
– Preferences to the higher priority process are added at the beginning.
–Keep the list sorted in increasing order.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

Circular Queue :

0 1 2 3 4 5 6 7

10 20 30 40 50

front rear

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

0 1 2 3 4 5 6 7

20 30 40 50

front rear

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue : Algorithm : Enqueue(Insert) operation on Circular Queue:

•Step 1: Check for queue full


If ((rear==max–1) and (front==0)) or if (front==rear+1) then print : circular queue is
full, insertion operation is not possible and return otherwise go to step 2
•Step 2: [if queue is empty i.e.]
If ((front == -1) AND (rear==-1)) then
set front=rear=0
Else if ((rear==max-1)AND(front!=0)) then
set rear = 0
else
set rear = rear+1
•Step 3: Insert element at the position pointed by rear pointer.
q[rear]=Data
•Step 4: Stop

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue : Algorithm : Dequeue(Delete) operation on Circular Queue:
void delete1()
•Step 1: [Check for queue empty ] {
if ((front == -1)AND(rear==-1)) then int val;
print : circular queue is empty, deletion operation is not if((front==-1)&&(rear==-1))
possible and return. { printf("\n\t Queue Empty");}
otherwise go to step 2 else
•Step 2: [copy data] {
Data = q[front] val=q[front];
•Step 3: printf("\n\t Value %d deleted from queue",val);
if(front==rear) then [if it is only one element then] if(front==rear)
set front = rear = -1 { front = -1;
else if(front= = max-1) then [if element at last position rear=-1; }
then] else if(front==max-1)
set front = 0 { front=0; }
else [otherwise] else
set front=front+1 { front++; }
}
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue : Circular Queue - Menu driven program

switch(ch)
#include<stdio.h> {
#include<conio.h> case 1:
#define max 5 insert();
void insert(); break;
void delete1(); case 2:
void display(); delete1();
int q[max],front=-1,rear=-1; break;
void main() case 3:
{ display();
int ch; break;
do case 4:
{ exit(0);
printf("\n\t Menu \n\t1.Insert default:
\n\t2.Delete \n\t3.Display printf("\n\t Invalid choice...");
\n\t4.Exit"); }
printf("\n\t Enter choice : "); }while(ch!=4);
scanf("%d",&ch); getch();
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :
void insert() //--------- insert function ------------------ //------ delete function ---------
{ void delete1()
int val; {
if(((front==0)&&(rear==max-1))||(front==rear+1)) int val;
{ printf("\n\t Queue Full"); } if((front==-1)&&(rear==-1))
else { printf("\n\t Queue Empty"); }
{ else
printf("\n\t Enter val : "); {
scanf("%d",&val); val=q[front];
if((front==-1)&&(rear==-1)) printf("\n\t Value %d deleted from queue",val);
front=rear=0; if(front==rear)
else if((rear==max-1)&&(front!=0)) front = rear = -1;
rear=0; else if(front==max-1)
else front=0;
rear++; else
q[rear]=val; front++;
} }
display(); display();
} }

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :
else //else2
//-------- display function ----------
{
void display()
for(i=0;i<=rear;i++)
{
{
int i;
printf("%d",q[i]);
printf("\n\t Current Status of Queue:");
}
if((front==-1)&&(rear==-1))
for(i=front;i<=max-1;i++)
{
{
printf("\n\t Queue Empty");
printf("%d",q[i]);
}
}
else //else1
}//else2
{
}//else1
if(front<=rear)
}//display()
{
for(i=front;i<=rear;i++)
{ printf("%d",q[i]); }
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

Double Ended Queue :


Double ended queues are double ended lists in which elements can be added or deleted from either end but
not from middle.
There are two ends namely left end and right end.
In double ended queue, element is inserted from any end i.e. either front or rear & element is deleted from
either front or rear end.

There are two types of Double Ended Queues as follows:


1. Input Restricted Double Ended Queue [IRD]
2. Output Restricted Double Ended Queue [ORD]

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Queue :

1. Input Restricted Double Ended Queue [IRD] :

It allows insertion only at one end of the list but allows deletion at both the ends of the list.

2. Output Restricted Double Ended Queue [ORD] :

It allows deletion only at one end of the list but allows insertion at both the ends of the list.

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack:

n factorial

0 1

1! 1*0!=1*1=1 1 * 1=1

2! 2*1!=2*1=2 2 * 1=2

3! 3*2!=3*2=6 3 * 2=6

4! 4*3!=4*6=24 4 * 6=24

5! 5*4!=5*24=120 5 *
24=120

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack:

// C program to find factorial of given number


#include <stdio.h>

// function to find factorial of given number


unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}

int main()
{
int num;
printf(“\n\t Enter any number: ”);
scanf(“%d”,&num);
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack: n fibonacci

fib(0) 0

fib(1) 1

fib(2) 1

fib(3) 2

fib(4) 3

13

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)
Stack:

// C program to find factorial of given int main() {


number int n, i;
#include <stdio.h> printf(“\n\tEnter the number for Fibonacci series:
”);
// function to display fibonacci series scanf(“%d”,&n);
int fib(int n)
{ printf("\n\tFibbonacci of %d: " , n);
if(n == 0) printf(“\n\t----------------------”);
{ return 0; } for(i = 0;i<n;i++) {
else if(n == 1) printf("\n\t %d ",fib(i));
{ return 1; } }
else }
{ return (fib(n-1) + fib(n-2));
}

Pimpri Chinchwad Polytechnic, Computer Department Data Structures Using ‘C’ (22317)

You might also like