You are on page 1of 77

R L JALAPPA INSTITUTE OF TECHNOLOGY

Dept.. of Computer Science & Engg.

Module 2

Iliyaz Pasha M
Assistant Professor

De
1 partment of Computer Science, RLJIT
Outline
 Stacks:
 Definition
 Stack Operations
 Array Representation of Stacks
 Stacks using Dynamic Arrays
 Stack Applications: Polish notation
 Infix to postfix conversion
 Evaluation of postfix expression
 Recursion:
 Factorial
 GCD
 Fibonacci Sequence
 Tower of Hanoi
 Ackerman's function.
 Queues:
 Definition, Array Representation, Queue Operations
 Circular Queues, Circular queues using Dynamic arrays
 Dequeues
 Priority Queues
 A Mazing Problem Department of Computer Science, RLJIT 2
 Multiple Stacks and Queues
Stacks
 A stack is a linear data structure in which an element may be
inserted or deleted at only one end ( i.e called as the top of the
stack).
 Stack is a data structure which works on the principle Last In
First Out (LIFO) i.e the Last element inserted will be the first
element to be deleted.

Department of Computer Science, RLJIT 3


Stacks
The various operations on stack are:
1. PUSH – Inserting an element into the stack.
2. POP – Removing or Deleting an element from the stack.
3. OVERFLOW – Check whether stack is full or not.
4. UNDERFLOW – Check whether stack is empty or not.

Department of Computer Science, RLJIT 4


Stacks
Implementation of Stacks ( using Arrays):-
1) create( ): The create stack function can be implemented as a one
dimensional array.

# define SIZE 5
int s[SIZE];
int top = -1;

Here, SIZE is symbolic constant, specifies the maximum number of


elements that can be inserted into stack.
s[SIZE] is an array, to hold the elements of the stack.

Department of Computer Science, RLJIT 5


Stacks
2) IsFull ( ) - Check for Overflow
In order to perform a Push Operation we need to check whether the
stack is completely filled with elements or not.

if ( top == SIZE -1 )
{
printf(“ Stack is Full or Overflow”);
return;
}

Department of Computer Science, RLJIT 6


Stacks
3) push( ): Insert an element into the stack.
First checks whether sufficient space is available in the stack. If
available the increment the value of top by 1(one), and then inserts
the item into the stack.
void push ( )
{
int item;

if ( top == SIZE -1 )
{
printf(“ Stack is Full or Overflow”);
return;
}

printf(“ Enter an item \n”);


scanf(“ %d”, &item);
s[++top] = item;
Department of Computer Science, RLJIT 7
}
Stacks
4) IsEmpty( ) - Check for Underflow
In order to perform a POP Operation we need to check whether the
stack is Empty or not.

if ( top == -1 )
{
printf(“ Stack is Empty or Underflow”);
return;
}

Note: top = = -1 indicates that the stack is empty.

Department of Computer Science, RLJIT 8


Stacks
5) pop( ): To delete an item from the stack.

void pop ( )
{
if ( top == -1 )
{
printf(“ Stack is Empty or Underflow”);
return;
}
printf(“Deleted item =%d”, s[top--]);
}

Department of Computer Science, RLJIT 9


Stacks
6) Display ( ): Print the contents of the stack.

void display ( )
{
int i;
if ( top == -1 )
{
printf(“ Stack is Empty or Underflow”);
return;
}
printf(“Contents of the stack are\n”);
for(i=top; i>=0; i--)
{
printf(“%d\t”, s[i]);
} Department of Computer Science, RLJIT 10
}
Write a C Program to implement stacks using arrays:
#include<stdio.h>
#define SIZE 5
int s[SIZE], top=-1;
void push ( )
{
int item;
if ( top == SIZE -1 )
{
printf(“ Stack is Full or Overflow”);
return;
}
printf(“ Enter an item \n”);
scanf(“ %d”, &item);
s[++top] = item;
}

Department of Computer Science, RLJIT 11


void pop ( )
{
if ( top == -1 )
{
printf(“ Stack is Empty or Underflow”);
return;
}
printf(“Deleted item =%d”, s[top--]);
}

void display ( )
{
int i;
if ( top == -1 )
{
printf(“Stack is empty or Underflow”);
return;
}
printf(“Contents of the stack are\n”);
for(i=top; i>=0; i--)
{
printf(“%d\t”, s[i]);
}
} Department of Computer Science, RLJIT 12
void main( )
{
int ch;
clrscr( );
for(;;)
{
printf(“ 1. Push \n 2. Pop \n 3. Display\n 4. Exit\n”);
printf(“Enter your Choice\n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: push( );
break;
case 2: pop( );
break;
case 3: display( );
break;
default: printf(“Invalid Choice\n”);
exit( 0);
}
} Department of Computer Science, RLJIT 13
}
Stacks using Dynamic Arrays
We can allocate or create a stack dynamically during run time.

#include <stdio.h>
#include <stdlib.h>
int size;
int top=-1;

void push(int stack[], int item)


{
if (top == size-1)
{
printf("The stack is full.\n");
return ;
}
stack[++top]=item;
} Department of Computer Science, RLJIT 14
Stacks using Dynamic Arrays
int pop(int stack[])
{
int d;
if(top==-1)
{
printf("The stack is empty.\n");
return (NULL);
}
d=stack[top--];
return (d);
}

Department of Computer Science, RLJIT 15


Stacks using Dynamic Arrays
void display(int stack[])
{
int i;
printf("The content of Stack are :\n");
for(i=top; i>=0; i--)
{
printf("%d \n",stack[i]);
}
}

Department of Computer Science, RLJIT 16


int main()
{
int *stack,data,ch;
printf("How many elements? : ");
. scanf("%d",&size);
stack=(int *)malloc(size*sizeof(int));
for(;;)
{
printf("Enter your choice(1.Push 2.Pop 3. Display 4.Exit :");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter data to push : ");
scanf("%d",&data);
push(stack,data);
break;
case 2: printf("Popped item is %d\n",pop(stack));
break;
case 3: display(stack);
break;
default : printf("Invalid Choice\n");
break;
}
Department of Computer Science, RLJIT
} 17
Stack Applications
 For Conversion from one form of expression to another. ( infix
to postfix)
 Evaluation of expression.
 To check parenthesis matching in an expression.
 For Memory Management.
 In Backtracking problems(Decimal to other number system,
Maze Tracer, Undo/Redo Operations, Depth First Search).
 Reversing data
 Finding Palindromes
 Recursive Operations

Department of Computer Science, RLJIT 18


Stack Applications: Polish notation
Expressions: It is sequence of operators and operands that
reduces to a single value after evaluation is called an expression.

a/b–c+d*e–a*c

In above expression contains operators (+, –, /, *) operands (a, b,


c, d, e,).

Expression can be represented in in different format such as


1. Infix Expression
2. Prefix Expression or Polish notation
3. Postfix Expression or Reverse Polish notation or suffix
expression.

Department of Computer Science, RLJIT 19


Stack Applications: Polish notation
Infix Expression: In this expression, the binary operator is placed in-between
the operand. The expression can be parenthesized or un- parenthesized.

Example: A + B

Here, A & B are operands and + is operator

Prefix or Polish Expression: In this expression, the operator appears before its
operand.

Example: + A B

Here, A & B are operands and + is operator

Postfix or Reverse Polish Expression: In this expression, the operator appears


after its operand.

Example: A B +
Department of Computer Science, RLJIT
Here, A & B are operands and + is operator 20
Stack Applications: Polish notation

Department of Computer Science, RLJIT 21


Precedence of the operators
In C, there is a precedence hierarchy that determines the order in which operators
are evaluated. Below figure contains the precedence hierarchy for C.

Department of Computer Science, RLJIT 22


Precedence of the operators
 The operators are arranged from highest precedence to
lowest. Operators with highest precedence are evaluated first.
 The associativity column indicates how to evaluate operators
with the same precedence. For example, the multiplicative
operators have left-to-right associativity. This means that
the expression a * b / c % d / e is equivalent to ( ( ( ( a * b ) /
c)%d)/e)
 Parentheses are used to override precedence, and expressions
are always evaluated from the innermost parenthesized
expression first .

Department of Computer Science, RLJIT 23


Infix to postfix conversion
Why to convert from infix to postfix or infix to prefix?
Compilers convert infix to postfix expression and then evaluate the
postfix expression. This is because:
 Infix expression are evaluated based on precedence and
associativity of operators. This way of evaluating is difficult and
time consuming.
 Evaluating postfix expressions and prefix expressions is easier.
The precedence and associativity of operators are not required.

Department of Computer Science, RLJIT 24


Infix to postfix conversion
How to write a program to convert a given infix expression to its equivalent
postfix expression?
Let us use two precedence function F and G. The function F contains the
precedence values of symbols on top of the stack and function G contains the
precedence values of symbols in the input string.
The precedence values associated with these two functions F and G are shown in
following table.
Symbols Stack Precedence Input Precedence Associativity
Function F Function G
+ ,- 2 1 Left
* , /,% 4 3 Left
$ or ^ 5 6 Right
Operands 8 7 Left
( 0 9 Left
) 0
# -1 Department of Computer Science, RLJIT 25
Infix to postfix conversion
C function which returns stack and input precedence values.
int F (char symbol) int G (char symbol)
{ {
switch(symbol) switch(symbol)
{ {
case „+‟ : case ‘+’ :
case „-‟ : return 2; case ‘-’ : return 1;
case „*‟ : case ‘*’ :
case „/‟ : return 4; case ‘/’ : return 3;
case „$‟ : case ‘$’ :
case „^‟ : return 5; case ‘^’ : return 6;
case „(‟ : return 0; case ‘(’ : return 9;
case „#‟ : return -1; case ‘)’ : return 0;
default: return 8; default : return 7;
} }
} }

Department of Computer Science, RLJIT 26


Infix to postfix conversion
Procedure: General procedure to convert from infix to postfix.
As long as the precedence of symbol on top of the stack is greater than the
precedence of input symbol, pop an item from the stack and place it in the postfix
expression.
while ( F (s[ top ]) > G (symbol) )
{
postfix[j++] = s[top--];
}

Once control comes out of the above loop, if the precedence of the symbol on top
of the stack is not equal to the precedence of the current input symbol, push the
current symbol on to the stack. Otherwise, delete an item from the stack.
if ( F (s[top]) != G (symbol) )
s[++top] == symbol;
else
top--;

Department of Computer Science, RLJIT 27


Convert the following infix expressions to postfix expressions : 1. a+(b-c)*(d-e)%f
Stack s[top] symbol F(s[top]) > G(symbol) Postfix
# # a -1 > 7 push
#a a + 8 > 1 pop a
# # + -1 > 1 push a
#+ + ( 2 > 9 push a
#+( ( b 0 > 7 push a
#+(b b - 8 > 1 pop ab
#+( ( - 0 > 1 push ab
#+(- - c 2 > 7 push ab
#+(-c c ) 8 > 0 pop abc
#+(- - ) 2 > 0 pop abc-
#+( ( ) 0 > 0 delete abc-
#+ + * 2 > 3 push abc-
#+* * ( 4 > 9 push abc-
#+*( ( d 0 > 7 push abc-
#+*(d d - 8 > 1 pop abc-d
#+*( ( - 0 > 1 push abc-d
#+*( - - ) 2 > 0 pop abc-de-
#+*( ( ) 0 > 0 delete abc-de-
#+ * * % 4 > 3 pop abc-de-*
#+ + % 2 > 3 push abc-de-*
#+% % f 4 > 7 push abc-de-*
Department of Computer Science, RLJIT 28
#+%f f Pop f abc-de-*f
#+% % Pop % abc-de-*f%
/*4. Design, Develop and Implement a Program in C for converting an Infix
Expression to Postfix Expression. Program should support for both
parenthesized and free parenthesized expressions with the operators: +, -, *,
/, %( Remainder), ^ (Power) and alphanumeric operands.*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int F (char symbol)
{
switch(symbol)
{
case '+':
case '-': return 2;
case '*':
case '/':
case „%‟:return 4;
case '$':
case '^': return 5;
case '(': return 0;
case '#': return -1;
default : return 8;
Department of Computer Science, RLJIT 29
}
int G (char symbol)
{
switch(symbol)
{
case '+':
case '-': return 1;
case '*':
case „/‟:
case „%': return 3;
case '$':
case '^': return 6;
case '(': return 9;
case ')': return 0;
default : return 7;
}
}

Department of Computer Science, RLJIT 30


void infix_postfix ( char infix[ ], char postfix[ ])
{
int top=-1,i=0,j=0;
char s[30], symbol;
s[++top] = '#';
for(i=0; i<strlen(infix); i++)
{
symbol=infix[i];
while ( F (s[ top ]) > G (symbol) )
{
postfix[j++] = s[top--];
}
if ( F (s[top]) != G (symbol) )
s[++top] = symbol;
else
top--;
}
while (s[top]!='#')
{
postfix[j++]=s[top--];
postfix[j]='\0';
}
}
Department of Computer Science, RLJIT 31
void main( )
{
char infix[20],postfix[20];
clrscr();
printf("Enter a valid infix expression\n");
scanf("%s",infix);
infix_postfix(infix,postfix);
printf("The postfix expression is\n");
printf("%s\n",postfix);
getch();
}

Department of Computer Science, RLJIT 32


Evaluation of postfix expression
Step 1: Scan the postfix expression from left to right.

Step 2: If the scanned symbol is an operand, then push it onto


the stack.

Step 3: If the scanned symbol is an operator, pop two symbols


from the stack ,assign to operand 2 and operand1 respectively.
Perform operation and push onto stack
op2= s[top--]
op1= s[top--]
perform the indicated operation
res = op1 Symbol op2
Push the result on to the stack

Step 4:Repeat the above procedure till the end of the input
Department of Computer Science, RLJIT
expression. 33
Evaluation of postfix expression
for( i=0; i < strlen(postfix); i++)
{
symbol = postfix[i];

if(isdigit(symbol))
s[++top] = symbol;
else
{
op2=s[top--];
op1=s[top--];

res= op1 symbol op2;


s[++top]=res;
}
}
Department of Computer Science, RLJIT 34
Evaluation of postfix expression
Design, Develop and Implement a Program in C for the
following Stack Applications
a. Evaluation of Suffix expression with single digit operands and
operators: +, -, *, /, %, ^
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>

int stack[20]; int pop()


int top = -1; {
if(top == -1)
void push(int x) return -1;
{ else
stack[++top] = x; return stack[top--];
} } of Computer Science, RLJIT
Department 35
void main ( )
{
char postfix[20],symb0l;
int op1,op2,i;
clrscr();
printf("\n\n Enter the postfix expression :: ");
gets(postfix);

for(i=0; i<strlen(postfix); i++)


{
symbol=postfix[i];
if(isdigit(symb)) // if digit- push digit to stack
push(symb -'0');

Department of Computer Science, RLJIT 36


else //if operator
{
op2=pop(); // pop second digit
op1=pop(); //pop first digit
switch(symb)
{
case '+':push(op1+op2);
break;
case '-':push(op1-op2);
break;
case '*':push(op1*op2);
break;
case '/':push(op1/op2);
break;
case '^':push(pow(op1,op2));
break;
}
}
}
printf("Result=%d",stack[top]);
getch(); Department of Computer Science, RLJIT 37
Evaluate (trace) the following Postfix Expressions. 123 + * 321 - + *

Postfix Symbol op2 op1 Result = op1 Symbol op1 Stack


Expression scanned Contents
123+*321-+* 1 1
23+*321-+* 2 12
3+*321-+* 3 123
+*321-+* + 3 2 Result=2+3 15
Result=5
*321-+* * 5 1 Result=1*5 5
Result=5
321-+* 3 53
21-+* 2 532
1-+* 1 5321
-+* - 1 2 Result=2-1 531
Result=1
+* + 1 3 Result=3+1 54
Result=4
* * 4 5 Result=5*4
Department of Computer Science, RLJIT
20
38
Result=20
Recursion
A recursive function is a function that calls itself during
execution.

The various types of recursion are shown below:


1. Direct recursion
2. Indirect recursion

Department of Computer Science, RLJIT 39


Recursion
1. Direct recursion: A recursive function that invokes itself is said
to have direct recursion.
For example, the factorial function calls itself and hence the
function is said to have direct recursion.
int fact ( int n)
{
if (n == 0)
return 1;
else
return (n*fact(n-1));
}

Department of Computer Science, RLJIT 40


Recursion
2. Indirect recursion: A function which contains a call to another
function which in turn calls another function which in turn calls
another function and so on and eventually calls the first function
is called indirect function.
For example, a function f1 invokes f2 which turn invokes f3
which in turn invokes f1 is said to have indirect recursion.

Department of Computer Science, RLJIT 41


Recursion
Requirements of Recursion:
1. Base Case or Terminal Condition: for which the procedure
0r function does not call itself.
2. Each time the procedure or function does call itself, it must
be closer to be base case. i.e. General case
3. Stack

Department of Computer Science, RLJIT 42


Recursion can be implemented for the following techniques:
1. Factorial of a number:-
Factorial function can be defined as:
a) If n=0, then n!=1
b) If n>0, then n!= n*(n-1)!
#include<stdio.h>
#include<conio.h>
int fact (int n)
{
if (n == 0)
return 1;
else
return (n*fact(n-1));
}

void main ( )
{
int n;
printf(“EnteraNumber\n”);
scanf(“%d”, &n);
printf(“Factorial = %d”, fact(n));
getch();
} Department of Computer Science, RLJIT 43
2. Fibonacci Sequence:-
The Fibonacci sequence is as follows:
0, 1,1, 2, 3, 5, 8, 13, 21, 34, 55, ………
i.e., F0=0 and F1=1, and each succeeding term is the sum of the two preceding terms
Fibonacci Sequence can be defined as:
a) If n=0, or n=1, then Fn=n
b) If n>1, then Fn= Fn-1 + Fn-2
#include<stdio.h>
#include<conio.h>
int fib (int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
else
return (fib(n-1) + fib(n-2));
}
void main ( )
{
int n;
printf(“EnteraNumber\n”);
scanf(“%d”, &n); Department of Computer Science, RLJIT 44
printf(“Fibonacci = %d”, fib(n));
3. Find GCD of 2 Numbers:-
#include<stdio.h>
#include<conio.h>
int gcd (int a, int b)
{
if (a == 0)
return b;
if (b == 0)
return a;
if (a>b)
return gcd(a%b, b);
else
return gcd(a, b%a);
}
void main ( )
{
int m,n;
printf(“Enter the values of m, n\”);
scanf(“%d%d”, &m,&n);
printf(“GCD of 2 Numbers is %d”, gcd(m,n));
getch(); Department of Computer Science, RLJIT 45
}
4. Tower of Hanoi:- Recursion may be used as a tool in solving the problem of
Tower of Hanoi.

Problem description:

Suppose three pegs (poles), labelled A, Band C, are given, and suppose on peg A
finite number n of disks with decreasing size are placed.

The objective of the game is to move the disks from peg A to peg C using peg B
as an auxiliary.

The rules of the game are as follows:


1. Only one disk may be moved at a time. Only the top disk on any peg may be
moved to any other peg.
2. At no time can a larger disk be placed on a smaller disk.

Department of Computer Science, RLJIT 46


Example: Towers of Hanoi problem for n = 3.

Solution: Observe that it consists of the following seven moves

1. Move top disk from peg A to peg C.


2. Move top disk from peg A to peg B.
3. Move top disk from peg C to peg B.
4. Move top disk from peg A to peg C.
5. Move top disk from peg B to peg A.
6. Move top disk from peg B to peg C.
7. Move top disk from peg A to peg C.

In other words, n=3: A→C, A→B,


C→B, A→C, B→A, B→C, A→C
For completeness, the solution to the
Towers of Hanoi problem for n = 1
and n = 2
n=l: A→C
Department of Computer n=2:
Science,A→B,
RLJIT A→C,
47
B→C
The Towers of Hanoi problem for n > 1 disks may be reduced to the following
sub-problems:
(1) Move the top n - 1 disks from peg A to peg B
(2) Move the top disk from peg A to peg C: A→C.
(3) Move the top n - 1 disks from peg B to peg C.

The general notation


 TOWER (N, BEG, AUX, END) to denote a procedure which moves the top n
disks from the initial peg BEG to the final peg END using the peg AUX as an
auxiliary.

 When n = 1, the solution:


TOWER (1, BEG, AUX, END) consists of the single instruction
BEG→END

 When n > 1, the solution may be reduced to the solution of the following
three sub- problems:
(a) TOWER (N - I, BEG, END, AUX)
(b) TOWER (l, BEG, AUX, END) or BEG → END
(c) TOWER (N - I, AUX, BEG, END)
Department of Computer Science, RLJIT 48
Procedure: TOWER (N, BEG, AUX, END)
This procedure gives a recursive solution to the Towers of Hanoi
problem for N disks.

1. If N=l, then:
(a) Write: BEG → END.
(b) Return.
[End of If structure.]

2. [Move N - 1 disks from peg BEG to peg AUX.]


Call TOWER (N - 1, BEG, END, AUX).

3. Write: BEG → END.

4. [Move N - 1 disks from peg AUX to peg END.]


Call TOWER (N - 1, AUX, BEG, END).

5. Return. Department of Computer Science, RLJIT 49


5. Design, Develop and Implement a Program in C for the following Stack
Applications
b. Solving Tower of Hanoi problem with n disks.
#include<stdio.h>
#include<conio.h>
void tower(int n, char S, char T, char D)
{
if(n == 0)
return;
tower(n-1, S, D, T);
printf("\nMove disc %d from %c to %c", n, S, D);
tower(n-1, T, S, D);
}
void main()
{
int n;
clrscr();
printf("\nEnter the number of discs: \n");
scanf("%d", &n);
tower(n, 'S', 'T', 'D');
getch(); Department of Computer Science, RLJIT 50
}
5. Ackermann function:
The Ackermann function is a function with two arguments each of
which can be assigned any nonnegative integer: 0, 1, 2, ....

Definition: (Ackermann Function)


(a) If m = 0, then A (m, n) = n + 1.
(b) If m > 0 but n = 0, then A(m, n) = A(m - 1, 1)
(c) If m > 0 and n > 0, then A(m, n) = A(m - 1, A(m, n - 1))

Department of Computer Science, RLJIT 51


/* Akerman Function*/
#include<stdio.h>
#include<stdlib.h>
int ack(int,int,int);
void main()
{
int m,n;
printf("Enter the value for m : ");
scanf("%d",&m);
printf("Enter the value for n : ");
scanf("%d",&n);
printf("The value is : %d\n",ack(m,n);
}

int ack(int m,int n,)


{
if(m==0) return(n+1);
else if(m>0 && n==0) return ack(m-1,1);
else return ack(m-1,ack(m,n-1));
Department of Computer Science, RLJIT 52
}
Queues
Queue is a linear data structure which works on the principle FIFO
(First In First Out) i.e. elements that is present in the queue for the
longest time will get deleted first.
Here insertion and deletion takes place at different ends: rear and
front.
Insertion into queue takes place at the rear end.
Deletion from the queue takes place at the front end.

Department of Computer Science, RLJIT 53


Queues
A queue is a special type of data structure where elements are inserted
from one end and elements are deleted from the other end. The end at
which new elements are added is called the rear and the end from
which elements are deleted is called the front.
Using this approach, the First element Inserted is the First element to
be deleted out, and hence , Queue is also called FIFO (First In First
Out) data structure.

Department of Computer Science, RLJIT 54


Queues
Types of Queues:-
1. Ordinary Queue (Linear Queue)
2. Double Ended Queue
3. Circular Queue
4. Priority Queue

The various operations performed on queue are:


Insert: An element is inserted from rear end.
Delete: An element is deleted from front end.
Overflow: If queue is full and we try to insert an item, overflow
condition occurs.
Underflow: If queue is empty and try to delete an item, underflow
condition occurs.
Note:
Queue can be implemented using arrays and linked lists.
Department of Computer Science, RLJIT 55
Queues
Ordinary Queue (Linear Queue):-
Linear Queue simply called a queue can be implemented using linear
list.
Implementation of Ordinary Queue using arrays:-
1. Create
#define QUEUE_SIZE 3
int q[QUEUE_SIZE];
int front = 0;
int rear = -1;
where QUEUE_SIZE is a symbolic constant and specifies the
maximum number of elements that can be inserted into the queue.
q is an array which is used to hold the elements of the queue.

Department of Computer Science, RLJIT 56


1. Insert( )
Before inserting, we first check for overflow i.e,
if ( rear == QUEUE_SIZE - 1)
{
printf(“Queue Overflow\n”);
return ;
}
When above condition fails, we can insert an item into the queue. To insert an item we
have to increment rear by 1(one) as shown below.
rear = rear + 1;
Then. The item can be inserted at the rear end of the queue using
q[rear] = item;
Now, the complete function can be written as shown below:
void insert ()
{
if ( rear == QUEUE_SIZE - 1)
{
printf(“Queue is Overflow or Queue is Full\n”);
return ;
}
printf(“Enter the item\n”);
scanf(“%d”,&item);
q[++rear] = item;
} Department of Computer Science, RLJIT 57
2. Delete( )
Before deleting, we first check for underflow i.e,
if (front > rear)
{
printf(“Queue is Underflow\n”);
return ;
}
When above condition fails, we can delete an item from front end of queue.
And increment front by 1(one) as shown below.
item = q[front++] ;
Now, the complete function can be written as shown below:
void del ()
{
if (front > rear)
{
printf(“Queue is Underflow\n”);
return ;
}
printf(“Element deleted = %d” , q[front++] );
}
Department of Computer Science, RLJIT 58
3. display( )
In the display function, if the queue already has some items, all those items are
displayed one after the other. If no items are present, the appropriate error
message is displayed.

void display ()
{
if (front > rear)
{
printf(“Queue is Underflow\n”);
return ;
}
printf(“Contents of Queue are:\n”);
for( i = front; i <= rear; i++)
{
printf(“%d\n”, q[i]);
}
}

Department of Computer Science, RLJIT 59


/*Queue implementation using arrays (Static implementation of Queues)*/
#include<stdio.h>
#include<conio.h>
#define QUEUE_SIZE 3
int i, front=0, rear=-1, item, q[QUEUE_SIZE];

void insert ()
{
if ( rear == QUEUE_SIZE - 1)
{
printf("Queue Overflow\n");
return ;
}
printf("Enter the item\n");
scanf("%d",&item);
q[++rear] = item;
}

Department of Computer Science, RLJIT 60


void del ()
{
if (front > rear)
{
printf("Queue is Underflow\n");
return ;
}
printf("Item deleted = %d\n",q[front++] );
}
void display ()
{
if (front > rear)
{
printf("Queue is Underflow\n");
return ;
}
printf("Contents of Queue are:\n");
for( i = front; i <= rear; i++)
{
printf("%d\t",q[i]);
} Department of Computer Science, RLJIT 61
}
void main( )
{
int ch;
clrscr( );
for(;;)
{
printf("1. Insert 2. Delete 3. Display 4. Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert( );
break;
case 2: del( );
break;
case 3: display( );
break;
default: printf("Invalid Choice\n");
exit(0);
}
} Department of Computer Science, RLJIT 62
}
Advantages of Ordinary Queue (Linear Queue):-
Simple and easy to implement.
Disadvantages of Ordinary Queue (Linear Queue):-
Consider the queue containing 3 elements 10, 20 and 30 are inserted.
If first 2 elements 10 and 20 are deleted. After that if we try to insert
an item we get error message is displayed like “Queue is overflow or
Queue is Full”.

In the above situation, even through space is available at the front end
we can’t insert the elements. i.e., rear insertion is denied.
How means before inserting an element will check one condition is
rear==QUEUE_SIZE-1. if this condition is satisfied it indicates
queue is full.
This disadvantage can be overcome by using 2 methods
1. Shift left
2. Circular Queue or Circular Representation
Department of Computer Science, RLJIT 63
Circular Queue :-
In circular queue, the elements of a given queue can be stored
efficiently in an array so as to “wrap around” so that end of the
queue is followed by the front of queue.
Before insertion the value of rear is calculated by
rear = (rear + 1) % QUEUE_SIZE
After deletion the value of front is calculated by
front = (front + 1) % QUEUE_SIZE
To check for overflow and underflow, global variable count is
maintained.
If count = = QUEUE_SIZE then Queue is Full or Overflow
If count = = 0 then Queue is empty or Underflow.

The operations of Circular Queue are:


 Insert
 Delete
 Display
Department of Computer Science, RLJIT 64
/* Implementation of Circular Queue using arrays (Static
implementation of Circular Queues)*/
#include<stdio.h>
#include<conio.h>
#define QUEUE_SIZE 3
int i, j, front=0, rear=-1, item, count=0, q[QUEUE_SIZE];

void insert ()
{
if ( count == QUEUE_SIZE )
{
printf("Queue is Overflow or Queue is Full\n");
return ;
}
printf("Enter the item\n");
scanf("%d",&item);
rear = (rear + 1)%QUEUE_SIZE;
q[rear] = item;
count++;
Department of Computer Science, RLJIT 65
}
void del ()
{
if (count == 0)
{
printf("Queue is Underflow or Queue is Empty\n");
return ;
}
printf("Item deleted = %d\n",q[front]);
front = (front + 1)%QUEUE_SIZE;
count--;
}

Department of Computer Science, RLJIT 66


void display ()
{
if (count == 0)
{
printf("Queue is Underflow or Queue is Empty\n");
return ;
}
j=front;
printf("Contents of Queue are:\n");
for( i = 1; i <= count; i++)
{
printf("%d\t",q[j]);
j = (j+1)%QUEUE_SIZE;
}
}

Department of Computer Science, RLJIT 67


void main( )
{
int ch;
clrscr( );
for(;;)
{
printf("\n 1. Insert 2. Delete 3. Display 4. Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert( );
break;
case 2: del( );
break;
case 3: display( );
break;
default:printf("Invalid Choice\n");
exit(0);
}
} Department of Computer Science, RLJIT 68
}
Advantages of Circular Queue:-
Optimal utilization of memory.
Disadvantages of Circular Queue:-
Keeping track of rear and front is difficult.

Department of Computer Science, RLJIT 69


Circular Queue using Dynamic Arrays:-
Before inserting, we check whether sufficient space is available in the
circular queue. We know that if count value is same as SIZE, then
circular queue is full. The code for this condition can be written as
shown below.
if( count == SIZE)
{
printf( “ Q Full\n”);
return;
}
But, once the queue is full, instead of returning the control, we can
increase the size of array using realloc( ) function and the above code
can be modified as shown below.
if ( count == SIZE )
{
printf(“ Q Full: Update size, insert item\n”);
SIZE++;
q = (int *) realloc(q, Department
SIZE*sizef(int));
of Computer Science, RLJIT 70
When above condition fails, it means we can insert an item. If the above condition is
true, space is not sufficient. So, using realloc( )we increase the size by 1. however it
is not sufficient to simply increase the size using realloc( ). The queue contents have
to be re-adjusted.
Case 1: The front index is less than the rear index:
Case 2: The front index is greater than the rear index:
if ( count == SIZE )
{
printf(“ Q Full: Update size, insert item\n”);
SIZE++;
q = (int *) realloc(q, SIZE*sizef(int));

if( front > rear)


{
for (i= QUEUE_SIZE-2; i>=front; i--)
{
q[i++] = q[i];
}
front++;
}
} Department of Computer Science, RLJIT 71
C program to implement Circular Queue using Dynamic Arrays:
#include<stdio.h>
#include<conio.h>
Int QUEUE_SIZE = 1;
int i, j, front=0, rear=-1, item, count=0, *q;

void insert( )
{
if ( count == SIZE )
{
printf(“ Q Full: Update size, insert item\n”);
SIZE++;
q = (int *) realloc(q, SIZE*sizef(int));

if( front > rear)


{
for (i= QUEUE_SIZE-2; i>=front; i--)
{
q[i++] = q[i];
}
front++;
}
}
Department of Computer Science, RLJIT
} 72
C program to implement Circular Queue using Dynamic Arrays:
#include<stdio.h>
#include<conio.h>
int QUEUE_SIZE = 1;
int i, j, front=0, rear=-1, item, count=0, *q;
void insert( )
{
if ( count == SIZE )
{
printf(“ Q Full: Update size, insert item\n”);
SIZE++;
q = (int *) realloc(q, SIZE*sizef(int));

if( front > rear)


{
for (i= QUEUE_SIZE-2; i>=front; i--)
{
q[i++] = q[i];
}
front++;
}
}
rear = (rear +1) % QUEUE_SIZE;
Department of Computer Science, RLJIT
q[rear] = item; 73
Advantages of Circular Queue over Linear Queue:
1. The circular queue allows the entire array to store the elements
without shifting any data within the queue.
2. The array of circular queue is wrapped around which makes the
rear of the queue adjacent to front. This helps in accessing first or
last element of the queue very efficiently.
3. In case of circular queue, after deletion operation the empty space
of the array can be utilized for storing new element.
4. In linear queue the element can be inserted by incrementing rear
pointer. Once rear reaches to maximum size and even through the
elements are deleted from the front end. The linear queue can’t
utilize those empty slots.
Note: thus basic advantage of circular queue over linear queue is that
one can efficiently use array space and there is no wastage of
memory.

Department of Computer Science, RLJIT 74


Double Ended Queue (Dequeue):
• Double Ended Queue is also a Queue data structure in which the
insertion and deletion operations are performed at both the ends
(front and rear).
• That means, we can insert at both front and rear positions and can
delete from both front and rear positions.

Department of Computer Science, RLJIT 75


Questions???
1. Define Stacks. Write the stack implementations for push and pop
functions using arrays.
2. Write a c program to implement a stack using dynamic array.
3. Write a C Program to Convert infix expressions to postfix
expressions.
4. Convert the following infix expressions to postfix expressions :
1. a+(b-c)*(d-e)%f
2. (a+b) * d – e / (f + a * d) +c
3. (( a / ( b – c + d)) * (e – f ) * g)
4. a+(b+c)+(b/d)*a+z*u
5. A-B/C(C*D$E)
5. Write a C Program to evaluate the Postfix Expressions. Also
evaluate (trace) the following Postfix Expressions.
123 + * 321 - + *
623+-382/+*2$3+ Department of Computer Science, RLJIT 76
Questions???
6. Define Recursion. Write recursive procedure for
(1) factorial of a number
(2) Tower of Hanoi
(3) GCD of 2 Numbers
(4) Fibonacci Sequence
7. Write a note on Ackermann function. Write its algorithm. Evaluate
A (1,2) using Ackermann function.
8. Define queues. List the different types of queues. Write the
implementation of ordinary queues using arrays.
9. List the disadvantages of linear queue and explain how it is solved
in circular queue. Give the algorithm to implement a circular queue
with suitable example.
10.Explain the implementation of circular queues using arrays.
(dynamically allocated arrays)
Department of Computer Science, RLJIT 77

You might also like