Stack and Queue1
Stack and Queue1
Structure
STACKS
Outline:
Definition
Representation of Stack in C
PUSH
POP
PEEP/PEEK
DISPLAY
Applications of Stack
Recursion
STACK
Definition: It is a non-primitive linear data structure into which a
new element can be added or from which an element can be deleted
at only one end called the top of the stack. The other end is called the
bottom of the stack.
Representation of Stack in C:
#define MAXSIZE 4
typedef struct
{
int
items[MAXSIZE];
int top;
}STACK; Page 1
Data
Structure
Basic Operations on Stack:
Push operation
Pop operation
Peep/peek operation
Display operation
Page 2
Data
Structure
POP Operation on Stack:
Deleting an element from the top of the stack is referred to as
Pop
operation.
If the stack is empty and an attempt is made to delete an
element from the stack then it results in a
situation called “Stack underflow”!!!
Condition to test for “Stack underflow” : if(top
== -1)
If this condition is true then it indicates that
Assume, MAXSIZE
is 3
Page 3
Data
Structure
#include<stdio.h
>
#include<stdlib.
h> #define
MAXSIZE 3
typedef struct
{
int
items[MAXSIZE];
int top;
}STACK;
int isfull(STACK s)
{
if(s.top==MAXSIZE-
1) return 1;
return 0;
}
int isempty(STACK s)
Page 4
Data
Structure
{
if(s.top==-1)
return 1;
return 0;
Page 5
Data
Structure
}
void PUSH(STACK *s,int data)
{
s->items[++s->top]=data;
printf("\n%d is pushed onto stack",data);
}
void DISPLAY(STACK s)
{
int i;
printf("\nSTACK CONTENTS:\nBOS->");
for(i=0;i<=s.top;i++)
printf("%d-
>",s.items[i]);
printf("TOS");
}
int main()
{
STACK s;
int
data,choice;
s.top = -1;
while(1)
{
printf("\n\n1:Push\n2:Pop\n3:Peek\n4:Display\n5:Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice)
; switch(choice)
{
case 1: if(isfull(s))
printf("\nSTACK OVERFLOW");
els
e
{ printf("\nEnter the data to be pushed: ");
scanf("%d",&data);
PUSH(&s,data);
}
Page 6
Data
Structure
break;
case 2: if(isempty(s))
Page 7
Data
Structure
printf("\nSTACK UNDERFLOW");
else
printf("\n%d is popped from top of the
stack",POP(&s)); break;
case 3: if(isempty(s))
printf("\nSTACK EMPTY");
else
PEEK(s);
break;
case 4: if(isempty(s))
printf("\nSTACK EMPTY");
else
DISPLAY(s);
break;
case 5:exit(0);
#include<stdio.h
>
#include<stdlib.
h>
#include<string.
h> #define
MAXSIZE 3
typedef struct
{
char items[MAXSIZE]
[25]; int top;
}STACK;
int isfull(STACK s)
{
if(s.top==MAXSIZE-
1) return 1;
return 0;
}
int isempty(STACK s)
Page 8
Data
Structure
{
if(s.top==-1)
return
1;
Page 9
Data
Structure
return 0;
}
void DISPLAY(STACK s)
{
int i;
printf("\nSTACK CONTENTS:\nBOS->");
for(i=0;i<=s.top;i++)
printf("%s-
>",s.items[i]);
printf("TOS");
}
int main()
{
STACK s;
int choice;
char
name[20];
s.top = -1;
while(1)
{
printf("\n\N1:Push\n2:Pop\n3:Display\
n4:Exit"); printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: if(isfull(s))
printf("\nSTACK
OVERFLOW"); else
{
printf("\nEnter the name to be pushed: ");
scanf("%s",name);
PUSH(&s,name);
}
break;
Page
10
Data
Structure
case 2: if(isempty(s))
printf("\nSTACK UNDERFLOW");
else
printf("\nName %s is popped from top of the stack",POP(&s));
break;
case 3: if(isempty(s))
printf("\nSTACK EMPTY");
else
DISPLAY(s);
break;
case 4: exit(0);
Expressions
Sequence of operands and operators that reduces to a
single value after evaluation is referred to as an
expression.
Operands can be either a constant or a variable.
Operators can be +, -, *, /, % and $ or ^.
Page
11
Data
Structure
Examples: +ab, *+abc etc.
Page
12
Data
Structure
Postfix expression/Reverse Polish expression/Suffix expression:
Problems:
Convert the following Infix expressions into its equivalent Prefix and Postfix
expressions:
1. a + b
2. a + b * c
3. a * (b + c)
4. (A + B) * (C - D)
Page
13
Data
Structure
5. 2 $ 3 $ 2
6. a + ((b + c) *
7. A $ B * C – D + E / F / (G
8. (( A + ( B – C ) * D) ^
Page
14
Data
Structure
Applications of Stack
Conversion of expression from one form to another
Evaluation of Prefix/Postfix expression
Recursion
Checking for string palindrome
Checking for validity of expression
Evaluation of Postfix
Page
15
Data
Structure
#include<stdio.h>
#include<ctype.h>
#include<math.h>
#define MAXSIZE 20
typedef struct
{
float
items[MAXSIZE];
int top;
}STACK;
Page
16
Data
Structure
op1-oP2;
Page
17
Data
Structure
case '*': return
oP1*oP2; case '/':
return oP1/oP2; case
'$':
case '^': return pow(oP1,oP2);
}
}
int main()
{
STACK s;
char
postfix[30],symb;
float
N1,N2,res,data; int
i;
s.top=-1;
for(i=0;postfix[i]!=„\0‟;i++)
{
symb=postfix[i];
if(isdigit(symb))
PUSH(&s,symb-'0');
else if(isalpha(symb))
{
printf("\n%c = ",symb);
scanf("%f",&data);
PUSH(&s,data);
}
else
{
N2=POP(&s);
N1=POP(&s);
res=compute(N1,Symb,N2);
PUSH(&s,res);
printf("\nResult of evaluation: %f",POP(&s));
return 0;
}
Page
18
Data
Structure
Evaluation of Prefix expression
Page
19
Data
Structure
Program: Develop a C program to evaluate the given prefix expression.
#include<stdio.h>
#include<string.h
>
#include<math.h>
#include<ctype.h
> #define
MAXSIZE 20
typedef struct
{
float
items[MAXSIZE]; int
top;
}STACK;
int main()
{
STACK s;
char
prefix[30],symb;
float
n1,N2,Res,data; int
i;
s.top=-1;
Page
21
Data
Structure
else if(isalpha(symb))
{
printf("\n%c = ",symb);
scanf("%f",&data);
PUSH(&s,data);
}
els
e
{ N1=POP(&s);
n2=POP(&s);
res=compute(n1,symb,n2);
PUSH(&s,res);
}
}
printf("\nResult of evaluation:
%f",POP(&s)); return 0;
}
Page
22
Data
Structure
#include<stdio.h>
#include<ctype.h>
#define MAXSIZE 25
typedef struct
{
char
items[MAXSIZE];
int top;
}STACK;
Page
23
Data
Structure
}
Page
24
Data
Structure
char POP(STACK *s)
{
return(s->items[s->top--]);
}
char PEEK(STACK s)
{
return(s.items[s.top]);
}
case '+':
case '-': return 1;
case '*':
case '/':
case '%': return 2;
case '$':
case '^': return 3;
}
}
int main()
{
STACK s;
char
infix[30],postfix[30],symb,ch; int
i,j=0;
s.top=-1;
PUSH(&s,'#');
for(i=0;infix[i]!='\0';i++)
{
symb=infix[i];
if(isalnum(symb))
postfix[j+
+]=symb;
Page
25
Data
Structure
else
{
Page
26
Data
Structure
switch(symb)
{
case '(': PUSH(&s,'(');
break;
default: while(preced(symb)<=preced(PEEK(s)))
{
if(symb==PEEK(s) &&
preced(symb)==3) break;
postfix[j++] = POP(&s);
}
PUSH(&s,symb);
}
}
while(PEEK(s)!='#') postfix[j+
+]=POP(&s);
postfix[j]='\0';
printf("\nResultant Postfix
Expression:\n"); printf("%s",postfix);
return 0;
}
Page
27
Data
Structure
Conversion of Infix expression to Prefix
Page
28
Data
Structure
Page
29
Data
Structure
Recursion
Definition: The process in which a function calls itself directly or
indirectly is referred to as recursion and the corresponding
function is called as a recursive function.
It should have at least one base case that doesn‟t involve call
to itself.
Iteration Recursion
It uses looping control constructs It uses conditional constructs
such
such as while, do while and for.
as if, if-else, switch.
It terminates when loop It terminates when the base case
condition is
fails. reached.
It becomes infinite when there is
It becomes infinite when
no base case or base case
loop condition never fails.
is never
reached.
It consumes less memory space It takes more time and consumes
and
more memory space.
executes faster.
It is not suitable for applications It is best suitable for applications
such as Towers of Hanoi, such as Towers of Hanoi,
Tree traversals etc. Tree traversals etc.
Tracing and debugging is easy Tracing and debugging is
difficult
Page
30
Data
Structure
Problem1: To find the factorial of a number.
//Recursive Function
int fact(int n)
{
if(n==0) // Base Case
return 1;
//Recursive Function
int mul(int a,int b)
{
if(a == 0 || b == 0) // Base Case
return 0;
return(a + mul(a,b-1)); //General Case
}
Page
31
Data
Structure
//Recursive Function
int sum(int n)
{
if(n == 1) // Base Case
return 1;
Page
32
Data
Structure
Problem4: To compute sum of squares of first n natural numbers.
//Recursive Function
int sum(int n)
{
if(n == 1) // Base Case
return 1;
return(n*n+sum(n-1)); //General
Case
//Recursive Function
float sum(int n)
{
if(n == 1) // Base Case
return 1;
Page
33
Data
Structure
//Recursive Function
int sum(int n)
{
if(n == 0) // Base Case
return 0;
Page
34
Data
Structure
Problem7: To compute xn
//Recursive Function
Page
35
Data
Structure
Problem8: To find the nth Fibonacci number (0 1 1 2 3 5….)
//Recursive Function
int fibo(int n)
{
if(n == 0 || n==1) // Base Case
return n;
return(fibo(n-1)+fibo(n-2)); //General
case
}
#include<stdio.h
{> int fibo(int n)
if(n == 0 || n == 1) // Base Case
return n;
int main()
{
int i,n;
Page
36
Data
Structure
printf(“\nEnter the value of n: “);
scanf(“%d”,&n);
printf(“\nFirst %d Fibonacci numbers:\n”,n);
for(i=0;i<n;i++)
printf(“%d ”,fibo(i));
return 0;
}
//Recursive Function
int gcd(int m,int n)
{
if(n == 0) // Base Case
return m;
return(gcd(n,m%n)); //General
Case
//Recursive Function
int sum(int a[],int n)
{
if(n == 0) // Base Case
return a[n];
return(a[n] + sum(a,n-1)); //General Case
}
Page
37
Data
Structure
a[0] a[1] a[2] a[3]
10 20 30 40
In main() function:
res = search(a,0,n-1,key);
//Recursive Function
int search(int a[],int low,int high,int key)
{
int mid;
Page
38
Data
Structure
return(search(a,mid+1,high,key);
}
//Recursive Function
int findLength(char str[],int i)
{
if(str[i]==„\0‟) //Base Case
return 0;
return(1+FindLength(str,i+1)); //General Case
}
Page
39
Data
Structure
Problem14: To search for a character in a string.
In main() function:
res = search(str,0,ch);
//Recursive Function
int search(char str[],int i,char ch)
{
if(str[i]==„\0‟) //Base Case for failure
return(-1);
if(str[i] == ch) //Base Case for success
return(i+1);
return(search(str,i+1,ch)); //General Case
}
//Recursive Function
int checkPalindrome(char str[],int i,int j)
{
if(i>=j) //Base Case for success
return(1);
if(str[i] != str[j]) //Base Case for failure
return(-1);
return(checkPalindrome(stR,I+1,j-1)); //General Case
}
Page
40
Data
Structure
Towers of Hanoi
Initial Setup for Towers of Hanoi
Page
41
Data
Structure
Recursive Solution for Towers of Hanoi Problem:
Base Case:
If the number of disks is 1, then transfer the disk from Peg A to Peg
C.
General Case:
Recursively transfer n-1 disks from Peg A to Peg B
using Peg C as auxiliary.
Transfer the nth disk from Peg A to Peg C.
Recursively transfer n-1 disks from Peg B to Peg C
using Peg A as auxiliary.
#include<stdio.h
> int moves;
void TOH(int n,char src,char temp,char dest)
{
if(n == 1)
{
printf(“\nTransfer disk %d from Peg %c to Peg
%c”,n,src,dest); moves++;
return;
}
TOH(n-1,src,dest,temp);
TOH(n-1,temp,src,dest);
}
int main()
{
int n;
printf(“\nEnter the number of disks: “);
scanf(“%d”,&n);
TOH(n,‟A‟,‟B‟,‟C‟);
return 0;
Page
42
Data
Structure
}
Page
43
Data
Structure
Page
44
Data
Structure
Page
45
Data
Structure
Page
46
Data
Structure
Page
47
Data
Structure
Page
48
Data
Structure
QUEUES
Outline:
Definition
Representation of Queue in C
Types of Queues
Linear Queue/Ordinary Queue
Circular Queue
Priority Queue
Double Ended Queue
Basic operations on Linear Queue
INSERT, DELETE, DISPLAY
Basic operations on Circular Queue
INSERT, DELETE, DISPLAY
Basic operations on Priority Queue
INSERT, DELETE, DISPLAY
Basic operations on Double ended Queue
INSERT, DELETE, DISPLAY
QUEUE
Definition: It is a non-primitive linear data structure in which a
new element can be inserted at one end called the rear end
and an element can be deleted from the other end called the
front end.
Representation of Queue in C:
#define
MAXSIZE4
typedef struct
{
int
items[MAXSIZE];
int f,r;
Page
49
Data
Structure
Types of Queues:
Linear Queue/Ordinary Queue
Circular Queue
Priority Queue
LINEAR QUEUE
Page
50
Data
Structure
Assume, MAXSIZE is 3
Page
51
Data
Structure
#include<stdio.h
>
#include<stdlib.
h> #define
MAXSIZE 3
typedef struct
{
char
items[MAXSIZE];
int f,r;
}QUEUE;
int isfull(QUEUE q)
{
if(q.r == MAXSIZE-1)
return 1;
return 0;
}
int isempty(QUEUE q)
{
Page
52
Data
Structure
if(q.f == -1)
return 1;
Page
53
Data
Structure
return 0;
}
void DISPLAY(QUEUE q)
{
int i;
printf("\nQUEUE CONTENTS:\nFRONT->");
for(i=q.f;i<=q.r;i++)
printf("%c-
>",q.items[i]);
printf("REAR");
}
int main()
{
QUEUE q;
int
choice;
char
data;
q.f=q.r=-1;
while(1)
{
printf("\n\N1:Insert\N2:Delete\n3:Display\
n4:Exit"); printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
Page
54
Data
Structure
{
case 1: if(isfull(q))
printf("\nQueue Overflow !!!");
else
Page
55
Data
Structure
{
printf("\nEnter the character to be inserted:
"); getchar();
scanf("%c",&data);
INSERT(&q,data);
}
break;
case 2: if(isempty(q))
printf("\nQueue Underflow !!!");
else
printf("\nCharacter \‟%c\‟ is deleted from queue",DELETE(&q));
break;
case 3: if(isempty(q))
printf("\nQueue is Empty !!!");
else
DISPLAY(q);
break;
case 4: exit(0);
Page
56
Data
Structure
Assume, MAXSIZE is 3 and the data to be inserted are 10, 20,
30, 40
Page
57
Data
Structure
printf(“Circular Queue Overflow”);
Page
58
Data
Structure
Deletion Operation on Circular Queue:
The statement used to update f is as follows:
f = (f+1)%MAXSIZE;
Page
59
Data
Structure
Display Operation on Circular Queue:
If f <= r then elements can be displayed from f to r.
typedef struct
{
int
items[MAXSIZE];
int f,r;
}QUEUE;
int isfull(QUEUE q)
{
if(q.f == (Q.R+1)%MAXSIZE)
return 1;
return 0;
}
int isempty(QUEUE q)
{
if(q.f == -1)
return 1;
return 0;
}
Page
60
Data
Structure
{
q->r=(q->r+1)%MAXSIZE;
Page
61
Data
Structure
q->items[q->r]=data;
printf("\n%d is inserted into circular
queue",data); count++;
if(q->f==-1)
q->f=0;
}
void DISPLAY(QUEUE q)
{
int i;
printf("\nQUEUE CONTENTS:\nFRONT->");
for(i=1;i<=count;i++)
{
printf("%d->",q.items[q.f]);
q.f=(q.f+1)%MAXSIZE;
}
printf("REAR");
}
int main()
{
QUEUE q;
int
choice;
int data;
q.f=q.r=-
1;
while(1)
{
printf("\n\N1:Insert\N2:Delete\n3:Display\
n4:Exit"); printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: if(isfull(q))
printf("\nCircular Queue Overflow !!!");
else
Page
62
Data
Structure
{
printf("\nEnter the data to be inserted: ");
Page
63
Data
Structure
scanf("%d",&data);
INSERT(&q,data);
}
break;
case 2: if(isempty(q))
printf("\nCircular QueueUnderflow
!!!"); else
printf("\n%d is deleted from
queue",DELETE(&q)); break;
case 3: if(isempty(q))
printf("\nCircular Queue is Empty
!!!"); else
DISPLAY(q);
break;
case 4: exit(0);
default: printf("\nInvalid choice");
}
}
return 0;
}
Page
64
Data
Structure
Variants of Dequeue:
Input-Restricted Dequeue
Output-Restricted Dequeue
Input-Restricted Dequeue
Definition: It is a non-primitive linear data structure in which
deletion operation can be performed at both the ends of the queue
but insertion operation can be performed at only one end of the
Page
65
Data
Structure
queue.
Page
66
Data
Structure
Output-Restricted Dequeue
Definition: It is a non-primitive linear data structure in which
insertion operation can be performed at both the ends of the queue
but deletion operation can be performed at only one end of the
queue.
#define
MAXSIZE 4
typedef struct
Page
67
Data
Structure
{
int
items[MAXSIZE];
int f,r;
}QUEUE;
Page
68
Data
Structure
void ins_right(QUEUE *q,int data)
{
q->items[++q->r] =
data; if(q->f == -1)
q->f = 0;
}
void display(QUEUE q)
{
int i;
printf(“\nDequeue Contents:\nFront-
>”); for(i = q.f;i<=q.r;i++)
printf(“%d->”,q.items[i]);
Page
69
Data
Structure
printf(“Rear”);
}
Page
70
Data
Structure
int main()
{
QUEUE q;
int choice,data;
q.f = q.r = -
1; while(1)
{
printf(“\n\n1:Ins_Right\n2:Ins_Left\n3:Del_Right\n4:Del_Left\n5:Display\n6:Exit”);
printf(“\nEnter your choice: “);
scanf(“%d”,&choice);
switch(choice)
{
case 1: if( q.r == MAZSIZE-1)
printf(“\nDequeue
Overflow”); else
{
printf(“\nEnter the data to be inserted: “);
scanf(“%d”,&data);
ins_right(&q,data);
printf(“\n%d is inserted at rear end of dequeue”,data);
}
break;
break;
== -1)
printf(“\nDequeue Underflow”);
else
printf(“\n%d is deleted from front end of dequeue”,del_left(&q));
Page
71
Data
Structure
break;
Page
72
Data
Structure
case 5: if( q.f == -1)
printf(“\nDequeue is
Empty”); else
display(q);
break;
case 6: exit(0);
default: printf(“\nInvalid choice”);
}
}
return 0;
}
Priority Queue
Definition: It is a non-primitive linear data structure in which the
elements are inserted or deleted based on some priority.
Page
73
Data
Structure
Each queue exhibits FIFO behaviour.
Each queue has its own pair of f and r.
Insertion Operation:
The elements are inserted into the appropriate queue
based on the priority.
Deletion Operation:
An element from queue0 is deleted first. Once queue0
becomes empty, element from queuE1 is deleted and so on.
#include<stdio.h
>
#include<stdlib.
h> #define
MAXSIZE 3
typedef struct
{
int
items[MAXSIZE];
int f,r;
}QUEUE;
q[p].items[++q[p].r] = data;
printf(“\n%d is inserted into Queue %d”,data,p);
if(q[p].f == -1)
q[p].f = 0;
}
}
Page
74
Data
Structure
void DELETE(QUEUE q[3])
{
int i,data;
for(i=0;i<3;i++)
{
if(q[i].f == -1)
printf(“\n\nQueue %d Underflow”,i);
els
e
{ data = q[i].items[q[i].f];
printf(“\n%d is deleted from queue %d”,data,i);
if(q[i].f == q[i].r)
q[i].f = q[i].r = -1;
else
q[i].f++;
return;
}
}
}
}
}
}
int main()
{
QUEUE q[3];
int i,p,choice;
for(i=0;i<3;i++)
q[i].f = q[i].r = -1;
while(1)
Page
75
Data
Structure
{
printf(“\n\N1:INSERT\N2:DELETE\n3:DISPLAY\n4:EXIT”);
Page
76
Data
Structure
printf(“\nEnter your choice:
“); scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\nEnter the
priority: “); scanf(“%d”,
&p);
if(p < 0 || p >2)
printf(“\nInvalid priority”);
else
INSERT(q,p);
break;
case 2: DELETE(q);
break;
case 3: DISPLAY(q);
break;
case 4: exit(0);
default: printf(“\nInvalid choice !!!”);
}
}
return 0;
}
Page
77
Data
Structure
Program: Implementation of Ascending Priority Queue.
#include<stdio.h
>
#include<stdlib.
h> #define
MAXSIZE 3
typedef struct
{
int
items[MAXSIZE];
int f,r;
}QUEUE;
int isfull(QUEUE q)
{
if(q.r == MAXSIZE-1)
return 1;
return 0;
}
int isempty(QUEUE q)
{
if(q.f == -1)
return 1;
return 0;
}
Page
78
Data
Structure
>f]; if(q->f == q-
>r)
q->f = q->r = -1;
else
q->f++;
Page
79
Data
Structure
return(data);
}
void DISPLAY(QUEUE q)
{
int i;
printf("\nQueue Contents:\nFront->");
for(i=q.f;i<=q.r;i++)
printf("%d-
>",q.items[i]);
printf("Rear");
}
int main()
{
QUEUE q;
int choice,data;
q.f = q.r = -
1; while(1)
{
printf("\n\N1:Insert\N2:Delete\n3:Display\
n4:Exit"); printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: if(isfull(q))
printf("\nQueue Overflow !!!");
els
e
{ printf("\nEnter the data to be
inserted: "); scanf("%d",&data);
INSERT(&q,data);
}
break;
case 2: if(isempty(q))
printf("\nQueue Underflow !!!");
else
printf("\n%d is deleted from queue",DELETE(&q));
break;
case 3: if(isempty(q))
printf("\nQueue is Empty !!!");
else
DISPLAY(q);
Page
80
Data
Structure
break;
Page
81
Data
Structure
case 4: exit(0);
Page
82