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

DS Unit 1

The document describes data structures and specifically stacks. It defines a stack as a last-in, first-out data structure where elements are inserted and removed from one end called the top. Key stack operations like push, pop, and display are described along with algorithms to implement these operations using an array. Examples are provided to illustrate stack operations and overflow/underflow conditions. Classification of linear and non-linear data structures is also covered.

Uploaded by

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

DS Unit 1

The document describes data structures and specifically stacks. It defines a stack as a last-in, first-out data structure where elements are inserted and removed from one end called the top. Key stack operations like push, pop, and display are described along with algorithms to implement these operations using an array. Examples are provided to illustrate stack operations and overflow/underflow conditions. Classification of linear and non-linear data structures is also covered.

Uploaded by

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

UNIT-1

Introduction to Data Structures


Abstract data type (ADT)
Stacks, Queues and Circular Queues and
their implementation with arrays
Stack Applications:
Infix to Post fix conversion
Postfix expression evaluation.
Applications of Queues

2
 Data can be represented in the form of binary digits in memory. A
binary digit can be stored using the basic unit of data called bit. A
bit
can represent either a zero or a one.

 Data means value or set of values or Data is a collection of raw


facts.

 Data structure is a way of storing and organizing data in an


efficient manner.

 Any data structure is designed to organize data to suit a specific


purpose so that it can be accessed and worked in appropriate ways
both effectively and efficiently.

3
 The main objective of the data structure is to store and
retrieve the data in effectively and efficiently.

 Mathematically, a data structure D is a triplet, that is,


D=(d, f, a) where

D= data structure
d= a set of variables (data objects)
f= a set of functions
a= set of rules to implement the functions.

4
Classification of Data Structures
 Several data structures are available in the computer science
and used based on their applications.
 Data structures are classified into different types.

Type
s

Linear Data Structures Non Linear Data Structures

Array Linked stac queue Tree Graph


s list k s s s

5
• Linear Data Structures: A data structure is said to be linear
if its elements form a sequence or a linear list.

• Non-linear Data Structures: A data structure is said to be


non linear if its elements are not in a sequence. The
elements in the data structure are not arranged in a
linear manner; rather it has a branched structure.

6
Abstract Data Type (ADT)
 Abstract Data Type is a
Declaration of data and
Declaration of operations.

 That is an Abstract Data Type (ADT) defines data together


with the
operations.

 ADT is specified independently of any particular


implementation.

 ADT depicts the basic nature or concept of the data


structure rather
than the implementation details of the data.

 A stack or a queue is an example of an ADT.


7
 Both stacks and queues can be implemented using an array
Stack ADT Example

struct stack
{
int top, size;
};
void push();
void pop();
void display();

8
Stacks
 A stack is a Last In First Out (LIFO) data structure in which all
insertions and deletions are takes place at one end, called the top.

 Stack maintains a variable called top, which keeps track of the top
most element in the stack.

 Any insertions or deletions should be based upon the value of top.

 In the stack, the elements are removed in the reverse order of that in
which they were added to the stack that is last element inserted is
to be deleted first.
Basic Stack Operations:
push/insert : To insert an item into stack
pop/delete : To delete an item from stack
traverse/display : To display an items
isFull : To know whether the stack is full or not
isEmpty : To know whether the stack is empty or not
9
A stack of cups

A stack of coins

10
Example 1:
When the elements are inserted in the order as A,B,C,D then the size
of the stack is 4 and the top most element in the stack is D.
When deletion operation is performed on stack continuously then the
order in which the elements are deleted is D,C,B,A.

D to
C to C p
B to B p B
A to A p A
p A

C to
p B to
B
p
A A A to
p

11
Example 2: Here Stack Size is
4
3 3 3
2 2 2
1 1 TOP-> 1 20
0 TOP-> 0 10 0 10

TOP = -1 Push 10 Push 20


(Empty stack)

TOP-> 3 40 TOP-> 3 40
3
TOP-> 2 2 30 2 30
30
1 20 1 20
1 20
0 10 0 10
0 10
Push 40 Push 50
Push 30
(Overflow)

12
3 3
TOP-> 2 30 2
1 20 TOP-> 1 20
0 10 0 10
pop pop

3 3
2
2
1 1
TOP-> 0 0
10
pop (TOP = -1)
pop underflow

13
Example:3

14
Example 4:

15
Implementing Stack using Array

A stack can be implemented either using an array or a linked list.

Procedure:

 Initialize the stack by assigning -1 to the top variable to indicate


that
the array based stack is empty.

 A top is an integer value, which contains the array index for the
top of
the stack.

 Each time data is pushed or popped, top is incremented or


decremented accordingly, to keep track of the current top of the
stack.
16
 Stacks implemented as arrays are useful if a fixed amount of data
Algorithm for inserting an element into the stack
Algorithm push()
1. if top>=size then
1. print “stack is
full”
2. else
1. read item
2. top=top+1
3. stack[top]=item
3. endif
4. stop
The first step of this algorithm checks for an overflow condition.

Overflow means inserting an item into a stack which is full.

If the top value reaches to maximum size of the stack then items cannot
be inserted into the stack i.e. stack is full.

Otherwise top is incremented by one and item is inserted into the stack.
17
Algorithm for deleting an element from the stack

Algorithm pop()

1. if top = -1 then
print “stack is empty”
2. else
1. item = stack[top]
2. top=top-1
3.endif
4.stop

The first step of this algorithm checks for underflow


condition.

If the top value is -1 then stack is known as underflow or


empty.

Takeout the element from the location where the top is


pointing and store it in the variable then decrement top by one.
18
Algorithm for displaying an elements of the stack

Algorithm display()
1. if top = -1
1.print “stack empty”
2. else
1. for(i = top; i >= 0;i--)
1.print “stack[i]”
3.endif
4. stop

If the top value is -1 then the stack is empty.

If stack is not empty, assign top value to variable i, display the


item which is pointed at stack[i] and decrement the top
value by one and repeat this until top becomes zero.

19
/*Week-1
Write a C program that implement stack and its operation by using the
arrays
Description:
In this program we have to implement the stack operation by using the
arrays. Here the stack operations are push and pop. Push operation is used
to insert the elements into a stack and pop operation is used to remove the
elements from the a stack
Program*/
# include <stdio.h>
# define SIZE 4
void push();
void pop();
void display();
int isEmpty();
int isFull();
int top=-1,stack[SIZE],item,choice;
void main(){
while(1){
printf(" *** MENU ***\n 1. PUSH\n 2. POP\n 3.DISPLAY\n 4.isEmpty\n 5.isFull\n 6.EXIT\n");
printf("enter your choice from menu:");
scanf("%d",&choice);
switch(choice){
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:isEmpty();
break;
case 5:isFull();
break;
case 6:exit();
default:printf("wrong choice\n");
}//switch
}//while
}
void push(){
if(top==size-1)
printf("*** stack overflow(full) ***\n");
else
{
printf("enter the item to be pushed into the stack:");
scanf("%d",&item);
top++;
stack[top]=item;
}
}
void pop(){
if(top==-1)
printf("*** stack is empty ***\n");
else
{
item=stack[top];
top--;
printf("the deleted item from stack
is %d\n",item);
}
void display(){
int i;
if(top==-1)
printf("**** stack
underflow****");
else
{
printf("*** stack display ***\n");
for(i=top;i>=0;i--)
if(i==top)
printf("%d at %d
->top\n",stack[i],i);
else
printf("%d at %d\
n",stack[i],i);
}
}
int isEmpty(){
if(top==-1)
printf("stack is
empty");
else
int isFull()
{
if(top==size-1)
printf("stack is full");
else
printf("stack is not full");
return 0;
}
Applications of Stack

The LIFO structure of the stack provides many applications


of
stack.
Applications:
1. Reversing an array of elements.
2. Converting an infix expression into RPN (Reverse Polish
Notation).
3. Evaluating a postfix or RPN expression.

25
Reversing an array of elements
Very easy application is to reverse the order of a given array of items.

Algorithm reverse(string)
1. Initialize an empty stack.
2. while not the end of string
2.1 read a character
2.2 push it on to the stack
3. end while
4.while the stack is nonempty
4.1 pop a character
4.2 print it
5.end while

26
Types of expressions
Arithmetic expressions can be represented in three ways:

Infix notation: The operator/operation is in between the two


operands.
Examples: A+B
2+3

Prefix (Polish notation): The operator precedes the operands.


Examples: +AB
+23

Postfix (Reverse Polish Notation): The operator follows the


operands.
Examples: AB+
27
23+
Notations – Conversions
Consider the infix expression: 2 + 3 * (5 – 7) /
9
Let us insert implicit parentheses
(2 + ((3 * (5 – 7)) / 9))

Transfer the operators to the beginning of parentheses


(+ 2 (/ (* 3 (– 5 7)) 9))
Remove the parentheses: + 2 / * 3 – 5 7 9
This is the equivalent prefix expression.

Transfer the operators to the end of parentheses


(2 ((3 (5 7 –) *) 9 /) +)
Remove the parentheses: 2 3 5 7 – * 9 / +
This is the equivalent postfix expression.
28
Examples
Infix
Prefix Expression Postfix Expression
Expression

2+3

2+3*5

(2 + 3) * 5

2 * 3 – (5 + 9)

29
2.INFIX TO RPN CONVERSION
Algorithm to convert infix expression to RPN:
1. Initialize an empty stack.
2. Repeat the following until the end of the infix expression is reached.
1. Get next input token (constant, variable, arithmetic operator, left
parenthesis, right parenthesis) in the infix expression.
2. If the token is
1. A left parenthesis: Push it onto the stack.
2. A right parenthesis:
1. Pop and display stack elements until a left parenthesis is on the
top of the stack.
2. Pop the left parenthesis also, but do not display it.
3. An operator:
1. While the stack is nonempty and token has lower or equal
priority than stack top element, pop and display.
2. Push token onto the stack.
4. An operand: Display it.
3. When the end of the infix expression is reached, pop and display stack
items until the stack is empty.
(Note: Left parenthesis in the stack has lowest priority)
An Example: 3*(9-2)+5
Remaining Infix String Stack Postfix String

3*(9-2)+5 empty null

*(9-2)+5 empty 3

(9-2)+5 * 3

9-2)+5 *( 3

-2)+5 *( 39

2)+5 *(- 39

)+5 *(- 392

+5 * 392-

5 + 392-*

null + 392-*5

31 null + 392-*5+
INFIX TO RPN CONVERSION – DEMO
Expression: Output:

3 ( 9 – 2 ) + 5 1. Scan a token.
*
1. 3 is an operand.
 2. Display 3.
S 2. Scan next token.
C 1. * is an operator.
A 2. Push * onto stack.
N 3. Scan next token.
1. ( --- left parenthesis.
2. Push ( onto stack.
4. Scan next token.
1. 9 is an operand.
2. Display 9.
5. Scan next token.
1. – is an operator.
2. Priority > that of (.
3. Push – .
6. Scan next token.
1. 2 is an operand.
2. Display 2.
7. Scan next token.
1. ) --- right parenthesis.
DEMO
Expression: Output: 3 9 2 –

+ 5 8. Scan next token.


• + is an operator.
 • Priority of + less than that of *
S • Pop * and display.
C • Stack is empty.
A • Push +
N
9. Scan next token.
• 5 is an operand.
• Display.
10. Scan next token.
• End of expression.
• Pop all elements and display.

*
An Example: 7-(2*3+5)*(8-4/2)  723*5+842/-*-
Remaining Infix String Stack Postfix String
7-(2*3+5)*(8-4/2) empty null
-(2*3+5)*(8-4/2) empty 7
(2*3+5)*(8-4/2) - 7
2*3+5)*(8-4/2) -( 7
*3+5)*(8-4/2) -( 72
3+5)*(8-4/2) -(* 72
+5)*(8-4/2) -(* 723
5)*(8-4/2) -(+ 723*
)*(8-4/2) -(+ 723*5
*(8-4/2) - 723*5+
(8-4/2) -* 723*5+
8-4/2) -*( 723*5+
-4/2) -*( 723*5+8
4/2) -*(- 723*5+8
/2) -*(- 723*5+84
2) -*(-/ 723*5+84
) -*(-/ 723*5+842
34
null empty 723*5+842/-*-
/*3i).Write a C program that uses stack operations to perform convertion of infix expression into
postfix expression.*/ for(i=0,j=0;i<l;i++)
#include<stdio.h> {
#include<ctype.h> if(isalpha(in[i]) || isdigit(in[i]))
#include<string.h> post[j+
static char stack[30]; +]=in[i];
int top=-1; else {
int push(char);
if(in[i]=='(')
char pop();
int priority(char); push(in[i]);
void main() else
{
char in[30],post[30],ch; if(in[i]==')') {
int i,j,l;
printf("\n Enter the string(Infix Expression): "); while((ch=pop())!='(')
gets(in);
post[j++]=ch;
l=strlen(in);
}
printf("\n The length of the given string is: %d\n",l);
else
{

while(priority(in[i])<=priority(sta
ck[top]))

post[j++]=pop();
35
push(in[i]);
while(top!=-1)
post[j++]=pop();
post[j]='\0';
printf("\nEquivalent infix to postfix is:%s ",post);
}//main
int priority (char c) {
switch(c) {
case '+':
case '-': return
1;
case '*':
case '/': return
2;
case '$': return
3;
case '^': return
4;
}//switch
return 0;c) {
int push(char
}//priority
stack[++top]=c;
return 0;
}//push
char pop(){
return (stack[top--]);
}//pop
36
3.EVALUATION OF RPN EXPRESSION
Algorithm evaluateRPN(expression)
1.Initialize an empty stack.
2.Do
1. Get next token (constant, variable, arithmetic operator) in
RPN expression.
2. If token is an operand, push it on the stack.
3. If token is an operator do the following:
1. Pop top two values from the stack. (If the stack does not contain
two items, report error.)
2. Apply operator token to these two values.
3. Push the resulting value onto the stack.
3.Until the end of the expression is encountered.
4.The value of the expression is on the top of the stack
(and stack should contain only this value).
– DEMO
Expression:
1. Scan a token.
2 4 * 9 5 + – 1. 2 is an operand.
 2. Push 2 onto stack.
S 2. Scan next token.
C 1. 4 is an operand.
A 2. Push 4 onto stack
N 8 3. Scan next token.
1. * is an operator.
2. Pop from stack --- 4.
3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 8 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.

Top 
EXPRESSION – DEMO
Expression: 1. Scan a token.
5 + – 1. 2 is an operand.
2. Push 2 onto stack.
 2. Scan next token.
S 1. 4 is an operand.
C 2. Push 4 onto stack
A 3. Scan next token.
N 14 1. * is an operator.
2. Pop from stack --- 4.
3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 6 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.
5. Scan next token.
1. 5 is an operand.
2. Push 5 onto stack.
6. Scan next token.
1. + is an operator.
Top  2. Pop
3. Pop
9 4. Apply +
5. Push result.
8 7. Scan next token.
1. - is an operand.
EXPRESSION – DEMO
Expression: 1. Scan a token.
– 1. 2 is an operand.
2. Push 2 onto stack.
 2. Scan next token.
S 1. 4 is an operand.
C 2. Push 4 onto stack
A 3. Scan next token.
1. * is an operator.
N 2. Pop from stack --- 4.
3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 6 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.
5. Scan next token.
1. 5 is an operand.
2. Push 5 onto stack.
6. Scan next token.
1. + is an operator.
2. Pop
3. Pop
Top  4. Apply +
5. Push result.
-6 7. Scan next token.
1. - is an operand.
EXPRESSION – DEMO
1. Scan a token.
Expression: 1. 2 is an operand.
2. Push 2 onto stack.
2. Scan next token.
 1. 4 is an operand.
S 2. Push 4 onto stack
3. Scan next token.
C 1. * is an operator.
-6 A 2. Pop from stack --- 4.
N 3. Pop from stack --- 2.
4. Apply * on the operands.
5. Push result 6 onto stack.
4. Scan next token.
1. 9 is an operand.
2. Push 9 onto stack.
5. Scan next token.
1. 5 is an operand.
2. Push 5 onto stack.
6. Scan next token.
1. + is an operator.
2. Pop
3. Pop
4. Apply +
5. Push result.
7. Scan next token.
1. - is an operand.
Top  2. Pop, pop, apply -, push result.
8. Scan next token
1. End of expression
Evaluate the postfix expression: 5 6 2 + * 12 4 / -
Remaining postfix String Symbol Scanned Stack
5 6 2 + * 12 4 / - no symbol empty
6 2 + * 12 4 / - 5 5
2 + * 12 4 / - 6 5
6+ * 12 4 / - 2 5 6 2
* 12 4 / - + 5 8
12 4 / - * 40
4 / - 12 40 12
/ - 4 40 12 4
- / 40 3
null - 37

42
/*3ii).Write a C program that uses Stack operations to perform the evaluation of the
postfix expression*/
#include<stdio.h>
#include<math.h>
void main() {
char postfix[30],t[30];
int stack[10],top=-1,len,i,j,op2,op1,n;
printf("\n\n\nEnter the postfix:");
gets(postfix);
len=strlen(postfix);
postfix[len]=‘#’;
for(i=0;postfix[i]!=‘#’;i++)
{
j=0;
if(postfix[i]==‘ ‘)
continue;
if(postfix[i]=='+'||postfix[i]=='-'||postfix[i]=='*'||postfix[i]=='/'||postfix[i]=='^')
{
op2=stack[top--];
op1=stack[top--];

43
switch(postfix[i]) {
case '+': stack[++top]=op1+op2;
break;
case '-': stack[++top]=op1-op2;
break;
case '*': stack[++top]=op1*op2;
break;
case '/': stack[++top]=op1/op2;
break;
case '^': stack[++top]=pow(op1,op2);
break;
}//end of switch
}//end of if
else {
while(postfix[i]!=‘ ‘) {
t[j++]=postfix[i++];
}
t[j]='\0';
n=atoi(t);
stack[++top]=n;
}
}//end of for
printf("\n\n\nResult=%d\n",stack[top]);
44 }//end of main
Queues

 A queue is a First In First Out (FIFO) data structure in which


elements are accessed from two different ends called Front and Rear.
The elements are inserted into a queue through the Rear end and are
removed from the Front end.

 A queue maintains two variables called Front and Rear. Front


refers
to the first position of the queue and Rear refers to the last position
of
the queue.

 In the Queue, the elements are removed in the order of that in


which they were added to the queue, that is first element inserted is
to be deleted first.
45
Basic Queue Operations:

Insertion: To add a new item to the rear end of the queue.


The rear end always points to the recently added element.

Deletion: To delete the item from front end of the queue.


The front end always points to the recently removed element.

Display: To display the items of queue.

46
Bus Stop Queue

Bus
Stop

front rear rear rear rear


rear

47
Bus Stop Queue

Bus
Stop

front rear rear


rear

48
Bus Stop Queue

Bus
Stop

front rear
rear

49
Bus Stop Queue

Bus
Stop

front rear
rear

50
front rear
New people must enter the queue at the
rear.

front
rear
People should leave the queue
from the front end.

rear
front
51
Types of Queues
 Linear Queue
 Circular Queue

 Linear Queue: It is the one in which the insertions are takes


place at rear end and deletions are takes place at front end.

 Circular Queue: It is the one in which the insertion of a new


element is done at the very first location of the queue if the
last
location of the queue is full. i.e. circular queue is one in
which the
first element comes just after the last element.

52
Working of a linear queue:
i) Initially front=rear= -1. It indicates queue is empty.
0 1 2 3 4

front=rear=-1

ii) Add 10 iii) Add 20


0 1 2 3 4 0 1 2 3 4
10 10 20

front rear front rear

iv) Add 30 v) Add 40


0 1 2 3 4 0 1 2 3 4
10 20 30 10 20 30 40

front rear front rear


53
vi) Add 50 vii) Add 60 (overflow)

0 1 2 3 4 0 1 2 3 4
10 20 30 40 50 10 20 30 40 50

front rear front rear

viii) delete (10 is removed) ix) delete (20 is removed)


0 1 2 3 4 0 1 2 3 4
20 30 40 50 30 40 50

front rear front rear

54
x) delete (30 is removed) xi) delete (40 is removed)

0 1 2 3 4 0 1 2 3 4
40 50 50

front front rear


rear

xii) delete (50 is removed) ix) delete (underflow)

0 1 2 3 4 0 1 2 3 4

rear front rear front

55
Implementing Queue using Array

A queue can be implemented either using an array or a linked list.

Procedure:

 Initialize the queue by assigning -1 to the front & rear variables to


indicate that the array based queue is empty.

 Each time data is inserted rear value is incremented by one and


when
data is deleted front value is also incremented by one.

56
Algorithm for inserting an element into the queue

Algorithm insert()
Explanation:
1. if rear >= size-1 then This procedure adds an item to the
1. print “queue queue.
is full”
2. exit First it checks for an overflow
2. else condition.
1. if rear = -1 If the rear value reaches or exceeds size
and front = -1 of the queue then elements cannot be
1. inserted into the queue. ie. Queue is full.
front = 0
2. endif Whenever element is inserted into the
queue, rear is increment by one and
3. rear = rear +
place the element in the location where
1
rear is pointing.
4. queue[rear]
= item
57
3. endif
Algorithm for deleting an element from the queue

Explanation:
Algorithm delete() This procedure deletes an element from
the queue.
1. if front = -1 or front >
rear then
The first step of this algorithm checks
1. print “queue for underflow condition.
is empty”
2. exit If the front value is -1 or front > rear
2. else then queue is empty.
1. item = Take out the element from the location
queue[front] where, the front is pointing and store it
2. front = front in the variable, then increment front by
+1 one.
3. endif
4. stop

58
Algorithm for displaying an elements from the queue

Algorithm display()
1. if front = = -1 or front >
rear then
1. print “queue is
empty”
2. exit
2. else
1. for(i = front; i
<= rear; i++)
1. print
“queue[i]”
If the front value 3.
is -1 or front > rear then the queue is empty.
endif
4. stop
If queue is not empty, display the item which is pointed at
queue[front] and increment the front value by one and
repeat this until front <= rear.
59
/*2.Write a C program that implement Queue and its operations using the arrays.
Description:This program implements the Queue operation by using the arrays. Here they Queue operation
are insertion and deletion. insertion operation is used to insert the elements into a Queue and deletion
operation is used to remove the elements from Queue*/
#include<stdio.h>
#include<stdlib.h>
#define size 4
void insertion();
void deletion();
void display();
int front=-1,rear=-1,item,choice,queue[size];
void main(){
while(1){
printf("\n*** MENU ***\n 1. INSERTION\n 2. DELETION\n 3.DISPLAY\n 4. EXIT\n");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice){
case 1 : insertion();
break;
case 2 : deletion();
break;
case 3 : display();
break;
case 4 : exit(0);
default : printf("*** wrong choice ***\n");
}//end of switch
}//end of while
}//end of main
void insertion()
{
if(rear>=size-1)
printf("*** queue is full ***\n");
else
{
printf("enter item into queue:");
scanf("%d",&item);
rear++;
queue[rear]=item;
if(front==-1)
front++;
}//end of else
}//end of insertion
void deletion()
{
if((front==-1)||(front>rear))
printf("*** queue is empty ***\n");
else
{
item=queue[front];
front++;
printf("the deleted item from queue is %d\
n",item);
}//end of else
}//end of delete function
void display()
{
int i;
if((front==-1)||(front>rear))
printf("*** queue is empty ***\n");
else
{
printf("\n elements in queue: ");
for(i=front;i<=rear;i++)
printf("%d ",queue[i]);
}//end of else
}//end of display function
/*2. Write a C program that implement Queue and its operations using the arrays*/
#include<stdio.h> #include<stdlib.h> #define size 4
void insertion(); void deletion(); void display();
int front=-1,rear=-1,item,choice,queue[size];
void main() {
while(1) {
printf("\n*** MENU ***\n 1. INSERTION\n 2. DELETION\n 3.TRAVERSE\n 4. EXIT\
n");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice) {
case 1 : insertion();
break;
case 2 : deletion();
break;
case 3 : display();
break;
case 4 : exit(0);
default : printf("*** wrong choice ***\n");
}//switch
}//while
}//main
65
void insertion() {
if(rear>=size-1)
printf("*** queue is full ***\n");
else {
printf("enter item into queue:");
void display() {
scanf("%d",&item);
int i;
rear++;
if((front = = -1)||(front>rear))
queue[rear] = item;
printf("*** queue is empty ***\
if(front = = -1)
n");
front++;
else {
}//else
printf("\n elements in queue:- ");
}//insertion
for(i=front;i<=rear;i++)
printf("%d ",queue[i]);
void deletion() {
}//else
if((front = = -1)||(front>rear))
}//display
printf("*** queue is empty ***\n");
else
{
item = queue[front];
front++;
printf("the deleted item from queue is %d\
n",item);
}//else
66 }//deletion
Circular Queue:

It is the one in which the insertion of a new element is done at the


very first location of the queue if the last location of the queue is
full. i.e. circular queue is one in which the first element comes
just after the last element.

A circular queue overcomes the problem of unutilized space in


linear queues implemented as arrays.

A circular queue also have a Front and Rear to keep the track of
elements to be deleted and inserted and therefore to maintain the
unique characteristic of the queue.

67
Circular Queue with size 5 After adding 5, 10, 20

After adding 30, 40


After deleting 5

Now Q[0] will be available in


the queue for another insertion
68
Insertion Algorithm: Deletion Algorithm:

1. if front == (rear+1)%size 1. if front = = -1


1. Queue is Overflow 1. Queue Underflow
2. if front == -1 2. delete item at cq[front]
1. front = rear = 0 3. if front = = rear
3. else 1. front = -1;
4. if rear == size - 1 2. rear = -1;
1. rear =0 4. else
5. else 5. if front = = SIZE-1
1. rear = rear + 1
1. front = 0;
6. read item; 6. else
7. cq[rear] = item 1. front = front+1;

69
Algorithm to Display :

1. front_pos = front, rear_pos = rear;


2. if front == -1
1. Queue is empty
3. if front_pos <= rear_pos
1. while front_pos <= rear_pos
1. print cq[front_pos]
2. front_pos++;
4. else
1. while front_pos <= SIZE-1
1. print cq[front_pos]
2. front_pos++;
2. front_pos = 0;
3. while front_pos <= rear_pos
1. print cq[front_pos]
2. front_pos++;

70
/* Program for circular queue using array*/
# include<stdio.h> # include<stdlib.h> # define
SIZE 4
int insert(); int del();
int display();
int cq[SIZE]; int front = -1;
int rear = -1;
main() {
int choice;
while(1) {
printf("1.Insert\n 2.Delete\n 3.Display\n 4.Quit\
n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice) {
case 1 : insert();
break;
case 2 : del();
break;
71 case 3: display();
break;
int insert() {
int item;
if(front == (rear+1)%SIZE) {
printf("Queue Overflow \n");
return;
}
if (front == -1) { /*If queue is empty */
front = 0;
rear = 0;
}
else if(rear == SIZE-1)/*rear is at last position of

queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in
queue : ");
scanf("%d", &item);
72 cq[rear] = item ;
return;
int del()
{
if (front == -1) {
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\
n",cq[front]);
if(front == rear) { /* queue has only one element */
front = -1;
rear = -1;
}
else if(front == SIZE-1)
front = 0;
else
front = front+1;
return;
}/*End of del() */
73
else
int display()
{
{
while(front_pos <=
int front_pos = front,rear_pos =
SIZE-1)
rear;
{
if(front == -1)
printf("%d
{
",cq[front_pos]);
printf("Queue is empty\
front_pos++;
n");
}
return;
front_pos = 0;
}
while(front_pos <=
rear_pos) {
printf("Queue elements :\n");
printf("%d
",cq[front_pos]);
if( front_pos <= rear_pos )
front_pos++;
while(front_pos <= rear_pos)
}
{
}/*End of else */
printf("%d
",cq[front_pos]);
printf("\n");
front_pos++;
74 return;
}
Applications of Queue

There are several applications of queues in computer science.

1. CPU scheduling in Multiprogramming environment- single CPU


has to serve more than one program simultaneously.
2. Operating System maintains a queue of processes that are ready
to process or that are waiting for particular event to occur.
3. Printer maintains a queue.
4. Call waiting when you are attending other call
5. A file server in a computer network handles file access request
from many clients throughout the network. Servers have a
limited capacity to service request from clients, when that
capacity is exceeded, client requests wait in queues.

75
Convert infix to postfix expression

1. (A-B)*(D/E)
2. (A+B^D)/(E-F)+G
3. A*(B+D)/E-F*(G+H/K)
4. ((A+B)*D)^(E-F)
5. (A-B)/((D+E)*F)
6. ((A+B)/D)^((E-F)*G)
7. 12/(7-3)+2*(1+5)
8. 5+3^2-8/4*3+6
9. 6+2^3+9/3-4*5
10. 6+2^3^2-4*5

76
Convert infix to postfix expression

1. (A-B)*(D/E)---AB-DE/*
2. (A+B^D)/(E-F)+G----ABD^+EF-/G+
3. A*(B+D)/E-F*(G+H/K) :-ABD+*E/FGHK/+*-
4. ((A+B)*D)^(E-F):-AB+D*EF-^
5. (A-B)/((D+E)*F)
6. ((A+B)/D)^((E-F)*G)
7. 12/(7-3)+2*(1+5)
8. 5+3^2-8/4*3+6
9. 6+2^3+9/3-4*5
10. 6+2^3^2-4*5
Evaluate the postfix expression

1. 53+2*697-/-
2. 35+64-*41–2^+
3. 31+2^741–2*+5-

78

You might also like