DSA Unit-2 CompleteNotes
DSA Unit-2 CompleteNotes
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.
Stack is also called as LIFO (Last In First Out) data structure since the last
element inserted will be the first to be removed from the stack.
Representation of Stack in C:
#define MAXSIZE 4
typedef struct
{
int items[MAXSIZE];
int top;
}STACK;
Assume, MAXSIZE is 3
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 3
typedef struct
{
int items[MAXSIZE];
int top;
}STACK;
int isfull(STACK s)
{
if([Link]==MAXSIZE-1)
return 1;
return 0;
}
int isempty(STACK s)
{
if([Link]==-1)
return 1;
return 0;
}
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<=[Link];i++)
printf("%d->",[Link][i]);
printf("TOS");
}
int main()
{
STACK s;
int data,choice;
[Link] = -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");
else
{
printf("\nEnter the data to be pushed: ");
scanf("%d",&data);
PUSH(&s,data);
}
break;
case 2: if(isempty(s))
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([Link]==MAXSIZE-1)
return 1;
return 0;
}
int isempty(STACK s)
{
if([Link]==-1)
return 1;
return 0;
}
void DISPLAY(STACK s)
{
int i;
printf("\nSTACK CONTENTS:\nBOS->");
for(i=0;i<=[Link];i++)
printf("%s->",[Link][i]);
printf("TOS");
}
int main()
{
STACK s;
int choice;
char name[20];
[Link] = -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;
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 ^.
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)
5. 2 $ 3 $ 2
6. a + ((b + c) * d)
7. A $ B * C – D + E / F / (G + H)
8. ( ( A + ( B – C ) * D) ^ E + F)
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
#include<stdio.h>
#include<ctype.h>
#include<math.h>
#define MAXSIZE 20
typedef struct
{
float items[MAXSIZE];
int top;
}STACK;
int main()
{
STACK s;
char postfix[30],symb;
float n1,n2,res,data;
int i;
[Link]=-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);
}
}
return 0;
}
#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;
[Link]=-1;
for(i=strlen(prefix)-1;i>=0;i--)
{
symb=prefix[i];
if(isdigit(symb))
PUSH(&s,symb-'0');
else if(isalpha(symb))
{
printf("\n%c = ",symb);
scanf("%f",&data);
PUSH(&s,data);
}
else
{
n1=POP(&s);
n2=POP(&s);
res=compute(n1,symb,n2);
PUSH(&s,res);
}
}
#include<stdio.h>
#include<ctype.h>
#define MAXSIZE 25
typedef struct
{
char items[MAXSIZE];
int top;
}STACK;
char PEEK(STACK s)
{
return([Link][[Link]]);
}
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;
[Link]=-1;
PUSH(&s,'#');
for(i=0;infix[i]!='\0';i++)
{
symb=infix[i];
if(isalnum(symb))
postfix[j++]=symb;
else
{
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';
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.
//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
}
//Recursive Function
int sum(int n)
{
if(n == 1) // Base Case
return 1;
//Recursive Function
int sum(int n)
{
if(n == 1) // Base Case
return 1;
//Recursive Function
float sum(int n)
{
if(n == 1) // Base Case
return 1;
//Recursive Function
int sum(int n)
{
if(n == 0) // Base Case
return 0;
Problem7: To compute xn
//Recursive Function
//Recursive Function
int fibo(int n)
{
if(n == 0 || n==1) // Base Case
return n;
Tracing:
#include<stdio.h>
int fibo(int n)
{
if(n == 0 || n == 1) // Base Case
return n;
int main()
{
int i,n;
return 0;
}
//Recursive Function
int gcd(int m,int n)
{
if(n == 0) // Base Case
return m;
//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
}
10 20 30 40
In main() function:
print(a,0,4);
//Recursive Function
int search(int a[],int low,int high,int key)
{
int mid;
return(search(a,mid+1,high,key);
}
In main() function:
findLength(str,0);
//Recursive Function
int findLength(char str[],int i)
{
if(str[i]==‘\0’) //Base Case
return 0;
return(1+findLength(str,i+1)); //General Case
}
In main() function:
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
}
In main() function:
res = checkPalindrome(str,0,strlen(str)-1);
//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
}
Towers of Hanoi
Initial Setup for Towers of Hanoi
Only one disk can be transferred at a time from any peg to any
other peg.
Larger disk can never be placed over the smaller disk.
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;
}
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.
Queue is also called as FIFO (First In First Out) data structure since
the first element inserted will be the first to be removed from the
Queue.
Representation of Queue in C:
#define MAXSIZE 4
typedef struct
{
int items[MAXSIZE];
int f,r;
}QUEUE;
Types of Queues:
Linear Queue/Ordinary Queue
Circular Queue
Priority Queue
LINEAR QUEUE
Since, Queue is full, data 7 cannot be inserted. This operation has resulted
in Queue Overflow.
Assume, MAXSIZE is 3
for(i=f;i<=r;i++)
printf(“%d->”,items[i]);
#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)
{
if(q.f == -1)
return 1;
return 0;
}
void DISPLAY(QUEUE q)
{
int i;
printf("\nQUEUE CONTENTS:\nFRONT->");
for(i=q.f;i<=q.r;i++)
printf("%c->",[Link][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)
{
case 1: if(isfull(q))
printf("\nQueue Overflow !!!");
else
{
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);
Assume, MAXSIZE is 3 and the data to be inserted are 10, 20, 30, 40
Since queue is full, data 40 cannot be inserted. This operation has resulted
in Queue Overflow.
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;
}
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->",[Link][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
{
printf("\nEnter the data to be inserted: ");
scanf("%d",&data);
INSERT(&q,data);
}
break;
case 2: if(isempty(q))
printf("\nCircular Queue Underflow !!!");
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;
}
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 queue.
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
{
int items[MAXSIZE];
int f,r;
}QUEUE;
void display(QUEUE q)
{
int i;
printf(“\nDequeue Contents:\nFront->”);
for(i = q.f;i<=q.r;i++)
printf(“%d->”,[Link][i]);
printf(“Rear”);
}
int main()
{
QUEUE q;
int choice,data;
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;
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.
Assume that the no. of queues are 3 and priority of queue0, queue1
and queue2 are 0, 1 and 2 respectively.
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;
}
}
for(i=0;i<3;i++)
{
if(q[i].f == -1)
printf(“\n\nQueue %d Underflow”,i);
else
{
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)
{
printf(“\n\n1:INSERT\n2:DELETE\n3:DISPLAY\n4:EXIT”);
case 2: DELETE(q);
break;
case 3: DISPLAY(q);
break;
case 4: exit(0);
default: printf(“\nInvalid choice !!!”);
}
}
return 0;
}
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;
}
return(data);
}
void DISPLAY(QUEUE q)
{
int i;
printf("\nQueue Contents:\nFront->");
for(i=q.f;i<=q.r;i++)
printf("%d->",[Link][i]);
printf("Rear");
}
int main()
{
QUEUE q;
int choice,data;
switch(choice)
{
case 1: if(isfull(q))
printf("\nQueue Overflow !!!");
else
{
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);
break;
case 4: exit(0);