DS Notes-1
DS Notes-1
RKDEMY
DEGREE / DIPLOMA ENGINEERING
SEM-III
DATA STRUCTURES
Computer & Information Technology
By -: Nitin Sir
1st floor new matruvandana society, near thane railway station behind kopri bus stop, Thane (east).
By Nitin Sir
2|RKDEMY
• Compiler Design,
• Operating System,
• Database Management System,
• Statistical analysis package,
• Numerical Analysis,
• Graphics,
• Artificial Intelligence,
By Nitin Sir
3|RKDEMY
By Nitin Sir
4|RKDEMY
• Traversing :
Traversing a data structure is accessing each data and accessing
only once.
• Searching :
Searching is finding the location of a data in within the given
data structure.
• Inserting :
Inserting is adding a new data in the data structure.
• Deleting :
Deleting is removing a data from the data structure.
• Sorting :
Sorting is arranging of data in some logical order.
• Merging :
Merging is combining of two similar data structures.
1. Top-down approach.
2. Bottom-up approach.
Top-Down Approach
By Nitin Sir
5|RKDEMY
Bottom-Up Approach
By Nitin Sir
6|RKDEMY
STACKS
What is stack
By Nitin Sir
7|RKDEMY
STACK as an ADT
Another variable “top” is used to keep track of the index of the top most
element.
By Nitin Sir
8|RKDEMY
Applications of Stack
• Expression Conversion
a) Infix to postfix c) postfix to infix
b) Infix to prefix d) prefix to infix
• Expression Evaluation
• Parsing
• Simulation of recursion
• Function Call
Implementation of Stack
• Stack can be easily implemented using an Array or a Linked List.
• Arrays are quick, but are limited in size and Linked List requires
overhead to allocate, but is not limited in size.
By Nitin Sir
9|RKDEMY
a) Initilize stack
void initialize (stack*s)
{
S→ top= -1;
}
By Nitin Sir
10 | R K D E M Y
return (1);
}
else
{
return (0);
}
}
By Nitin Sir
11 | R K D E M Y
#include<stdio.h>
#include<conio.h>
#define MAX 6
typedef struct stack
{
int data[MAX];
int top;
}stack;
void init(stack *);
int empty(stack *);
int full(stack *);
int pop(stack *);
void push(stack *, int );
void print(stack *);
void main( )
{
stack s;
int x, op;
init(&s);
do{
printf(“\n\n1)Push\n2)Pop\n3)Print\n4) Quit”);
printf("\n Enter Your choice : ");
scanf("%d", &op);
switch(op)
{
case 1:print(“\n enter a number:”);
scanf(“%d”,&x);
if(!full(&s))
push(&s,x);
else
printf(“\n Stack is full……”);
break;
case 2:if(!empty (&s))
{
x=pop(&s);
printf(“\n popped value = %d”,x);
}
else
printf(“\nStack is empty……….”);
break;
By Nitin Sir
12 | R K D E M Y
case 3:print(&s);
break;
}
}while( op != 4);
}
void init(stack *s)
{
s->top = -1;
}
int empty(stack *s)
{
if(s->top==-1)
return(1);
else
return(0);
}
int full(stack *s)
{
if(s->top==MAX-1)
return(1);
else
return(0);
}
void push(stack *s,int x)
{
s->top = s->top + 1;
s->data[s->top] = x;
}
int pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
return(x);
}
void print(stack *s)
{
int i;
printf(“\n”);
for(i=s->top; i>=0; i--)
{
printf(“%d”,s->data[i]);
By Nitin Sir
13 | R K D E M Y
}
}
By Nitin Sir
14 | R K D E M Y
(𝟐𝟏)𝟏𝟎 = ( ? )𝟐
21 % 2 =1
1
10 % 2 =0
0
1
1
5%2=1
0
1
0
2%2=0 1
0
1
1%2=1
1
0
1
0
1
By Nitin Sir
15 | R K D E M Y
#include <stdio.h.>
#include<conio.h>
#include<ctype.h>
#define MAX 50
typedef struct stack
{
int data [MAX];
int top;
}stack;
void init(stack*);
int empty(stack*);
int full(stack*);
int pop(stack*);
void push(stack*,int);
void main()
{
stack s;
int x;
init(&s);
printf(“Enter a decimal number\n”);
scanf(“%d”, &x);
while((x!=0)
{
if(!full(&s))
{
push(&s, x%2);
x=x/2;
}
else
{
printf(“Stack overflow”);
}
}
while (!empty(&s))
{
x=pop(&s);
printf(“%d”,x);
}
getch();
By Nitin Sir
16 | R K D E M Y
}
void init(stack *s)
{
S→top= -1;
}
int empty (stack *s)
{
if(s→top ==-1)
return(1);
else
return(0);
}
int full(stack *s)
{
if(s→top = = MAX-1)
return(1);
else
return(0);
}
void push(stack *s, intx)
{
s→top=s→top+1;
s→data[s→top]=x;
}
int pop (stack *s)
{
int x;
x= s→data[s→top];
s→top= s→top-1;
return(x);
}
Expression representation
By Nitin Sir
17 | R K D E M Y
Given Expression
5 3+ 9* +
6
3+9*+
5
+ 9 * +
3
5
9 * +
8
6
* + 9
By Nitin Sir
18 | R K D E M Y
+
72
Next token is an operator “+” , pop two operands 72 and 6 , add them
and push the result back on the stack.
78
#include <stdio.h.>
#include<conio.h>
#include<ctype.h>
#define MAX 50
typedef struct stack
{
int data [MAX];
int top ;
}stack;
void init(stack*);
int empty(stack*);
int full(stack*);
int pop(stack*);
void push(stack*,int);
void main()
{
stack s;
int x;
int op1, op2,val;
By Nitin Sir
19 | R K D E M Y
init(&s);
printf(“Enter the expression\n”);
while((x=getchar())!=’\n’)
{
if(isdigit(x))
{
push(&s, x-48);
}
else
{
Op2=pop(&s);
Op1=pop(&s);
Val=evaluate(x,op1,op2);
Push(&s,val);
}
}
Val=pop(&s);
Printf(“\n value of expression=%d”,val);
getch();
}
int evaluate(char x, int op1, int op2)
{
If(x==’+’)
return(op1+op2);
If(x==’-’)
return(op1-op2);
If(x==’*’)
return(op1*op2);
If(x==’/’)
return(op1/op2);
If(x==’%’)
return(op1%op2);
}
void init(stack *s)
{
S→top= -1;
}
By Nitin Sir
20 | R K D E M Y
1 (A+B)*C-D/E*(F/G) Empty -
2 A+B)*C-D/E*(F/G) ( -
3 +B)*C-D/E*(F/G) ( A
By Nitin Sir
21 | R K D E M Y
4 B)*C-D/E*(F/G) (+ A
5 )*C-D/E*(F/G) (+ AB
6 *C-D/E*(F/G) Empty AB+
7 C-D/E*(F/G) * AB+
8 -D/E*(F/G) * AB+C
9 D/E*(F/G) - AB+C*
10 /E*(F/G) - AB+C*D
11 E*(F/G) -/ AB+C*D
12 *(F/G) -/ AB+C*DE
13 (F/G) -* AB+C*DE/
14 F/G) -*( AB+C*DE/
15 /G) -*( AB+C*DE/F
16 G) -*(/ AB+C*DE/F
17 ) -*(/ AB+C*DE/FG
18 END -* AB+C*DE/FG/
19 END Empty AB+C*DE/FG/*-
Given Expression =(A+B)*C-D/E*(F/G).
Postfix Expression = AB+C*DE/FG/*-
By Nitin Sir
22 | R K D E M Y
_getch();
}
void Infix_To_Postfix(char infix[], char postfix[])
{
stack s;
char token, x;
int i, j = 0;
init(&s);
for (i = 0; infix[i] != '\0'; i++)
{
token = infix[i];
if (isalnum(token))
{
postfix[j++] = token;
}
else if (token == '(')
{
push(&s, token);
}
else if (token == ')')
{
while ((x = pop(&s)) != '(')
{
postfix[j++] = x;
}
}
else
{
while (precedence(token) <= precedence(top(&s)) && !empty(&s))
{
x = pop(&s);
postfix[j++] = x;
}
push(&s, token);
}
}
while (!empty(&s))
{
x = pop(&s);
postfix[j++] = x;
}
postfix[j] = '\0';
}
int precedence(char x)
{
if (x == '(')
return(0);
if (x == '+' || x == '-')
return(1);
if (x == '*' || x == '/')
return(2);
return(3);
}
void init(stack* s)
{
s->top = -1;
}
int empty(stack* s)
{
if (s->top == - 1)
return (1);
By Nitin Sir
23 | R K D E M Y
else
return(0);
}
void push(stack* s, int x)
{
s->top = s->top + 1;
s->data[s->top] = x;
}
int pop(stack* s)
{
int x;
x = s->data[s->top];
s->top = s->top - 1;
return(x);
}
int top(stack* p)
{
return(p->data[p->top]);
}
C program to convert:
1.Postfix to Infix
2.Postfix to Prefix
3.Prefix to Infix
#include<stdio.h>
#include<conio.h>
#include<string.h>
# define MAX 20
typedefstruct stack
{
int data [MAX];
int top ;
}stack;
char str[MAX],stack[MAX];
int top=-1;
void push(char c)
{
stack[++top]=c;
}
char pop()
{
By Nitin Sir
24 | R K D E M Y
return stack[top--];
}
void post_in()
{
inti,n;
char a,b,op;
printf("Enter the postfix expression\n");
gets(str);
gets(str);
n=strlen(str);
for(i=0;i<MAX;i++)
stack[i]=NULL;
printf("Infix expression is:\t");
printf("%c",str[0]);
for(i=1;i<n;i++)
{
if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
{
b=pop();
//a=pop();
op=str[i];
printf("%c%c",op,b);
}
else
{
push(str[i]);
}
}
printf("%c",str[top--]);
}
void post_pre()
{
inti,n;
printf("Enter the postfix expression\n");
gets(str);
gets(str);
n=strlen(str);
By Nitin Sir
25 | R K D E M Y
void pre_in()
{
intn,i;
char a,b,op;
printf("Enter the prefix expression\n");
gets(str);
gets(str);
n=strlen(str);
for(i=0;i<MAX;i++)
stack[i]=NULL;
printf("Infix expression is:\t");
for(i=0;i<n;i++)
{
if(str[i]=='+'||str[i]==''||str[i]=='*'||str[i]=='/')
{
push(str[i]);
}
else
{
op=pop();
a=str[i];
printf("%c%c",a,op);
}
}
printf("%c",str[top--]);
}
void main()
{
int opt;
clrscr();
while(1)
{
By Nitin Sir
26 | R K D E M Y
printf("\n........MENU.......");
printf("\n\t1.Postfix to Infix\n\t2.Postfix to Prefix\n\t3.Prefix to
Infix\n\t4.Exit\n");
scanf("%d",&opt);
switch(opt)
{
case 1:post_in();break;
case 2:post_pre();break;
case 3:pre_in();break;
case 4:exit();
default:printf("Invalid choice");break;
}
}
Factorial (n) =1
= n* factorial(n-1)
By Nitin Sir
27 | R K D E M Y
scanf(“%d”,&n);
ans=fact(n);
printf(“Factorial of %d is %d” ,n,ans);
return 0;
}
#include<stdio.h>
#include<conio.h>
int exponential (int , int);
void main()
{
int n , x , y;
printf(“Enter the value of x and n \n”);
scanf(“%d %d”,&x , &n);
y = exponential(x, n);
printf(“the value of x raise to is %d”,y);
getch();
}
int exponential (int x , int n)
{
By Nitin Sir
28 | R K D E M Y
int ans;
if(n == 1)
{
return x ;
}
else
{
ans= x * exponential(x, n-1);
return(ans);
}
}
OUTPUT:
enter the values of x and n
2
6
the value of x raise to n is 64
#include<stdio.h>
#include<conio.h>
int compute(int);
void main()
{
int no ,sum;
printf(“Enter a number \n”);
scanf(“%d”,&no);
sum= compute (no);
printf(“sum of number from 1 to n %d”,sum);
getch();
}
int compute (int n)
{
int ans;
if(n = = 1)
{
By Nitin Sir
29 | R K D E M Y
return 1 ;
}
else
{
ans= n + compute(n-1);
return(ans);
}
}
Output :-
Enter a number
10
Sum of 1 to n is 55.
#include<stdio.h>
#include<conio.h>
int fibo(int);
Void main()
{
int n,i,c,f;
printf(“Enter a number of terms”);
scanf(“%d”, &n);
for(c=1;c<=n;c++)
{
f=fibo(i);
printf(“%d”,f);
i++
}
getch();
}
int fibo(int n)
{
if(n==0)
{
return 0;
}
By Nitin Sir
30 | R K D E M Y
else if(n==1)
{
return 1;
}
else
{
return (fibo(n-1) + fibo (n-2));
}
}
By Nitin Sir
31 | R K D E M Y
#include <stdio.h>
#include <conio.h>
int sum(int n)
{
if(n==0)
return 0 ;
else
return( n%10 + sum(n/10) ) ;
}
void main()
{
int n,ans ;
printf("Enter the number: ") ;
scanf("%d" , &n) ;
ans= sum(n);
printf("Sum of digits of %d is %d" , n ,ans) ;
getch() ;
}
Output:
By Nitin Sir
32 | R K D E M Y
Important Questions
• Write a program in ‘C’ to evaluate a postfix expression. [M-10 Dec-13]
• Explain infix, postfix and prefix expressions with example[ M-6 May-
15]
• Write a c program to convert infix expression into postfix expr [M-10
May-15,May-14].
• Write a c program to convert a polish notation to reverse polish
notation.[M-10 Dec-14].
• Explain ADT. list linear and Non-linear data structure [M-5 DEC
17,DEC 16].
• Explain Stack as an ADT. Give applications of stack [M-5 DEC 16]
• What are various operations on data structure. [M-5 DEC-18]
• Using data structure to check well formatted of parentheses in an
algebraic expression. Write c program for same.
• Explain different types of data structure with example [M-5 May-18,
May-17]
• Write a program in ‘C’ to evaluate postfix expression using stack ADT
[M-10 May-18]
• Explain ADT. List the linear and non linear data structure with
example. [M-5 DEC-17]
• Write a program to convert infix expression into postfix expression.
[M-10, DEC-17, DEC-16]
By Nitin Sir
33 | R K D E M Y
QUEUES
Q.1 What is Queue
• It is a special kind of list, where items are inserted at one end (the
rear) and deleted from the other end(front).
• Queue is FIFO (First In First Out) list.
By Nitin Sir
34 | R K D E M Y
#define MAX 30
typedef struct Queue
{
int data [MAX];
int front , rear;
}Queue;
By Nitin Sir
35 | R K D E M Y
By Nitin Sir
36 | R K D E M Y
By Nitin Sir
37 | R K D E M Y
#include<stdio.h>
#include<conio.h>
#define MAX 30
typedef struct Queue
{
int data[MAX] ;
int F, R;
}Queue;
void initialize(Queue *p);
int empty (Queue *P);
int full (Queue *p);
void enqueue (Queue *p, int x);
int dequeue (Queue *p);
void print (Queue * p) ;
void main()
{
int x, ch, n;
Queue q;
init(&q);
do
{
printf(“1-create\n 2-insert\n 3-delete\n 4-Display 5-End\n”)
printf(“Enter your choice n”);
scanf(“%d”,&ch);
switch(ch)
By Nitin Sir
38 | R K D E M Y
{
case 1:
printf(“enter no of elements\n”);
scanf(“%d”,&n);
init(&q);
printf(“enter the data\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
}
break;
Case 2:
printf(“enter the element to be inserted”);
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
Case 3:
if(empty(&q))
{
printf(“queue is empty”);
By Nitin Sir
39 | R K D E M Y
Exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;
Case 4:
display(&q);
break;
default:
}
}while(ch!=5);
getch();
}
void initialize(Queue *p)
{
p→R=-1;
p→F=-1;
}
int empty (Queue *P)
{
if (p→R == -1)
return(1);
else
return(0);
}
By Nitin Sir
40 | R K D E M Y
By Nitin Sir
41 | R K D E M Y
int i;
for(i=p→F;i<= p→R;i++)
{
printf(“%d”,p→data[i]);
}
}
#include<Stdio.h>
#include<conio.h>
#define MAX 30
typedef struct Q
{
int data[MAX] ;
int F, R;
}Q;
void initialize(Q *p) ;
int empty (Q *P) ;
int full (Q *p) ;
void enqueue (Q *p, int x);
int dequeue (Q *p);
void print (Q * p) ;
void main()
{
int x, OP, n;
Q q;
printf(“enter no of elements\n”);
scanf(“%d”,&n);
By Nitin Sir
42 | R K D E M Y
init(&q);
printf(“enter the data\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
exit(0);
}
else
{
enqueue(&q,x);
}
}
do
{
printf(“1-Insert an element \n 2-Deleting an element\n 3-
displaying the queue\n 4-Exit the program.\n”)
printf(“Enter your choice n”);
scanf(“%d”,&op);
switch(op)
{
case 1:
printf(“enter the element to be inserted”);
Scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
case 2:
By Nitin Sir
43 | R K D E M Y
if(empty(&q))
{
printf(“queue is empty”);
exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;
case 3:
print(&q);
break;
default:
break;
}
}while(op!=4);
getch();
}
void initialize(Q *p)
{
p→R= - 1;
p →F= -1;
}
int empty (Q *P)
{
if (p ->R == -1)
return(1);
else
return(0);
}
By Nitin Sir
44 | R K D E M Y
if(p→R == MAX-1);
return (1);
else
return(0);
}
void enqueue (Q *p, int x)
{
if (p→R == -1) /*empty queue */
{
p→R =p→F=0;
p→data [p→R] = x;
}
else
{
p→R=p →R+1;
p →data [p→R]=x;
}
}
void print (Q * p)
{
By Nitin Sir
45 | R K D E M Y
int i;
for (i=p→F; i <= p→R;i++)
{
printf(“%d”,p→data[i]);
}
}
Circular Queues
There is one potential problem with implementation of queue using a simple
array.
The queue may appear to be full although there may be some space in the
queue.
By Nitin Sir
46 | R K D E M Y
i i=(i+1) % MAX
0 (0+1) % 5 =1
1 (1+1)%5 =2
2 (2+1)%5 =3
3 (3+1)%5 =4
By Nitin Sir
47 | R K D E M Y
typedef struct Q
{
int data ;
int R,F;
}Q;
By Nitin Sir
48 | R K D E M Y
}
else
{
p→R=(p→R+1)%MAX;
}
p→data[p→R] = x;
}
By Nitin Sir
49 | R K D E M Y
#include<stdio.h>
#include<conio.h>
#define max 30
typedef struct Q
{
int data[MAX] ;
int F, R
}Q;
void initialize(Q *p) ;
Int empty (Q *P) ;
Int full (Q *p) ;
void enqueue (Q *p, int x);
int dequeue (Q *p);
void print (Q * p) ;
void main()
{
int x, op, n;
Q q;
init(&q);
do
{
Printf(“1-create\n 2-insert\n 3-delete\n 4-print\n”)
printf(“Enter your choice n”);
scanf(“%d”,&op);
switch(op)
{
case 1: printf(“enter no of elements\n”);
scanf(“%d”,&n);
printf(“enter the data\n”);
for(i=0;i<n;i++)
{
By Nitin Sir
50 | R K D E M Y
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
}
break;
Case 2:
printf(“enter the element to be inserted”);
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
Case 3:
if(empty(&q))
{
printf(“queue is empty”);
Exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;
By Nitin Sir
51 | R K D E M Y
Case 4:
print(&q);
break;
default:
break;
}
}while(op!=5);
getch();
}
void initialize(Q *p)
{
p-→R= - 1;
p →F= -1;
}
int empty (Q *P)
{
if (p→R == -1)
return(1);
else
return(0);
}
By Nitin Sir
52 | R K D E M Y
{
p→R=(p→R+1)%MAX;
}
p→data[p→R] =
x;
}
int dequeue (Q * p)
{
int x;
x=p→data[p→F];
if (p→R = = p→F) /* last element */
p→R = p→F=-1;
else
p→F = (p→F+1)%MAX
;
return (X);
}
void print (Q * p)
{
int i;
i = p→ F; /* start from front */
while ( i! =p→R)
{
printf(“%d”, p→data[i]);
i=(i+1)%MAX ;
}
printf(“%d”, p→data[p-R]);
}
By Nitin Sir
53 | R K D E M Y
Priority Queue
1. Circular array
2. Linked list
By Nitin Sir
54 | R K D E M Y
By Nitin Sir
55 | R K D E M Y
p→rear=(p→rear + 1)%max;
}
Int dequeue (Q * p)
{
int x;
x=p→ data[p→F];
if (p→R = = p→F)
{
p→F=-1;
p→R=-1;
}
else
{
p→F = (p→F+1)%MAX ;
}
return (X);
}
void print (Q * p)
{
int i;
i = p→F; /* start from front */
while (i! =p→R)
{
printf(“\n %d”, p→data[i]);
i=(i+1)%MAX ;
}
printf(“%d”, p→data[p→R]);
}
By Nitin Sir
56 | R K D E M Y
#include<stdio.h>
#include<conio.h>
#define max 30
typedef struct Q
{
int data[MAX] ;
int F, R
}Q;
void initialize(Q *p) ;
Int empty (Q *P) ;
Int full (Q *p) ;
void enqueue (Q *p, int x);
int dequeue (Q *p);
void print (Q * p) ;
void main()
{
int x, op, n;
Q q;
init(&q);
do
{
printf(“1- Insert in a priority queue \n 2-delete\n 3-display\n 4-
exit \n”)
printf(“Enter your choice n”);
scanf(“%d”,&op);
switch(op)
{
case 1:
printf(“enter the element to be inserted”);
scanf(“%d”,&x);
if (full(&q))
By Nitin Sir
57 | R K D E M Y
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
case 2:
if(empty(&q))
{
printf(“queue is empty”);
Exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;
case 3:
print(&q);
break;
default:
break;
}
}while(op!=4);
getch();
}
By Nitin Sir
58 | R K D E M Y
By Nitin Sir
59 | R K D E M Y
break;
}
i =(i+1)%max /*insert*/
/*re-adjust error*/
P→data[i]= x;
P→rear=(P→rear + 1)%max;
}
}
Int dequeue (Q * p)
{
int x;
x=p→ data[p→F];
if (p→R = = p→F)
{
p→F=-1;
p→R=-1;
}
else
{
p→F = (p→F+1)%MAX ;
}
return (X);
}
void print (Q * p)
{
int i;
i = p→F; /* start from front */
while (i! =p→R)
{
printf(“\n %d”, p→data[i]);
i=(i+1)%MAX ;
}
printf(“%d”, p→data[p→R]);
}
By Nitin Sir
60 | R K D E M Y
Explain circular queue and double ended queue with example [10M
DEC16].
Dequeue
It is double ended queue.
Operation on dequeue :-
By Nitin Sir
61 | R K D E M Y
5. Give ADT for Queue data structure, discuss two applications of queue
data structure.[5M MAY17]
7. Explain circular queue and double ended queue with example [10M
DEC16].
10. Write an algorithm to create doubly linked list and display list
[10M May-18 (IT)]
By Nitin Sir
62 | R K D E M Y
By Nitin Sir
63 | R K D E M Y
Linked list
Data next
What is linked list? State its advantage, Explain its types [3M DEC-18]
By Nitin Sir
64 | R K D E M Y
2. No Random Access
In array we can access nth element easily just by using a[n].
In Linked list no random access is given to user, we have to access
each node sequentially.
3 . Time Complexity
Array can be randomly accessed , while the Linked list cannot be
accessed Randomly.
Linked list is a self referential structure in “c”. each node has variable to store
data and next field store the address of next field.
By Nitin Sir
65 | R K D E M Y
• In this type of linked list each node holds two pointer field.
• In doubly linked list address of next as well as preceding element
are linked with current node.
Head
What is the difference between Singly Linked List and Doubly Linked
List?
• Each element in the singly linked list contains a reference to the next
element in the list, while each element in the doubly linked list
contains references to the next element as well as the previous
element in the list.
By Nitin Sir
66 | R K D E M Y
• Doubly linked lists require more space for each element in the list and
elementary operations such as insertion and deletion is more complex
since they have to deal with two references.
• But doubly link lists allow easier manipulation since it allows
traversing the list in forward and backward directions.
• Each Node will store the data and address of the next node to be
followed.
Head
1. Traversing
2. Creating
3. Inserting
4. Deleting
5. Merging
6. Sorting
7. Searching
By Nitin Sir
67 | R K D E M Y
Algorithm
1. Obtain space for new node.
2. Assign data to the data field of the new node.
3. Set the next field of the new node to the beginning of the linked list.
4. Change the reference pointer of the linked list to point to the new
node.
By Nitin Sir
68 | R K D E M Y
5 10 15 x
Algorithm:
By Nitin Sir
69 | R K D E M Y
By Nitin Sir
70 | R K D E M Y
p→data=x;
p→next=NULL;
if(loc==1)
{
p→next=head;
return(p);
}
else
{
q=head;
for(i=1;i<=loc-1;i++)
{
if(q!=NULL)
{
q=q→next;
}
else
{
printf(“\n Overflow);
return(head);
}
p→next=q→next;
q→next=p;
return(head);
}
}
5 10 15
By Nitin Sir
71 | R K D E M Y
Algorithm
– Store the address of the first node in a pointer variable, say p.
– Move the head to the next node.
– Free the node whose address is stored in the pointer variable P.
By Nitin Sir
72 | R K D E M Y
5 10 15
Algorithm
2. If the first node itself is the last node then [make the linked list empty]
3. Position a pointer q on first node
4. Traverse in the list till q reach to previous node of last node
5. Position a pointer ‘p’ on last node
6. Free node whose address is store in pointer ‘p’
7. Set q→ next to null.
By Nitin Sir
73 | R K D E M Y
Algorithm
1. p=head
2. If the data in node p is x then
End search with success i.e. return(1)
3.Continue searching p=p→next.
4.If linked list end then end with failure i.e. return(0)
5.go to step 2
6.stop.
5 10 15
By Nitin Sir
74 | R K D E M Y
By Nitin Sir
75 | R K D E M Y
}
getch();
}
Write a ‘C’ program to create a single linked list which support following
operations. [10M May-18, Dec-18,
#include<stdio.h>
#include<conio.h>
typedef struct node
{
Int data;
Struct node *next;
}node;
node* create();
node* insert_b(node * head, intX);
node* insert_e(node * head, intx);
node* delete(node * head);
void print(node* head);
void main()
{
int op, x;
node * head=null;
do
{
printf(“1-create\n 2-insert in beginning \n 3-Insert at end\n 4-
delete a specific\n 5-display\n 6-quit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&op);
switch(op)
{
case1:
By Nitin Sir
76 | R K D E M Y
head=create();
break;
case2:
printf(“enter the data to be inserted\n);
scanf(“%d”,&x);
head=insert_b(head, x);
break;
case3:
printf(“enter data to be inserted\n”);
scanf(“%d”,&x);
head=insert_e(head, x);
break;
case4:
printf(“enter the data to be deleted\n”);
scanf(“%d”,&x);
head=delete(head,x);
break;
case5:
print(head);
break;
default:
}
}while(op!=6);
getch();
}
void create ()
{
node *head, *p;
int n, x, i;
printf(“ Enter no of items”);
scanf(“%d”, &n);
head=(node*)malloc(sizeof(node));
//read the data in 1st node
scanf(“%d”, &(head->data));
head->next=null;
p=head;
for(i=1;i<n;i++)
{
p->next=(node*)malloc(sizeof(node));
By Nitin Sir
77 | R K D E M Y
p=p->next;
p->next=NULL;
scanf(“%d”, &(p->data));
}
}
By Nitin Sir
78 | R K D E M Y
By Nitin Sir
79 | R K D E M Y
5 10 15
By Nitin Sir
80 | R K D E M Y
q=q→next;
}
q→next=p;
p→next=head;
head= p;
return(head);
}
}
5 10 15
By Nitin Sir
81 | R K D E M Y
}
}
5 10 15
p
void delete_b(node * head)
{
node *p;
if(head→next==head);
{
p=head;
free(p);
head=null
return (head);
}
else
{
q=head;
while (q→next!=head)
{
q=q→next;
}
p=head;
q→next=head→next;
head=head→next;
free(p);
return (head);
}
}
By Nitin Sir
82 | R K D E M Y
5 10 15
By Nitin Sir
83 | R K D E M Y
{
node *p;
if(head→data==head);
{
free(p);
head=null
return (head);
}
else
{
q=head;
while ((q→next)→next!=head)
{
q=q→next;
}
p=q→next;
q→next=null;
free(p);
return (head);
}
}
By Nitin Sir
84 | R K D E M Y
node* create();
node* insert_b(node * head, intX);
node* insert_e(node * head, intx);
node* delete(node * head);
void print(node* head);
void main()
{
int op, x;
node * head=null;
do
{
printf(“1-create\n 2-insert in beginning \n 3-Insert at end\n 4-
delete a specific\n 5-display\n 6-quit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&top);
switch(op)
{
case1:
head=create();
break;
case2:
printf(“enter the data to be inserted\n);
scanf(“%d”,&x);
Head=insert_b(head, x);
break;
case3:
printf(“enter data to be inserted\n”);
scanf(“%d”,&x);
By Nitin Sir
85 | R K D E M Y
head=insert_e(head, x);
break;
case4:
printf(“enter the data to be deleted\n”);
scanf(“%d”,&x);
head=delete(head,x);
break;
case5:
print(head);
break;
default:
}
}while(op!=6);
getch();
}
void create ()
{
node *head, *p;
int n, x, i;
printf(“ Enter no of items”);
scanf(“%d”, &n);
head=(node*)malloc(sizeof(node));
//read the data in 1st node
scanf(“%d”, &(head->data));
head->next=head;
p=head;
for(i=1;i<n;i++)
{
p->next=(node*)malloc(sizeof(node));
p=p->next;
p->next=head;
scanf(“%d”, &(p->data));
}
By Nitin Sir
86 | R K D E M Y
By Nitin Sir
87 | R K D E M Y
q=head;
while(q→next != head)
{
q=q→next;
}
q→next=p;
p→next=head;
return(head);
}
}
By Nitin Sir
88 | R K D E M Y
If(head!=null)
{
p=head;
while(p→next!=head);
{
printf(“%d”,p→data);
p=p→next;
}
printf(“%d”,p→data);
}
}
By Nitin Sir
89 | R K D E M Y
By Nitin Sir
90 | R K D E M Y
head =p;
head→next=head→prev=NULL;
}
else
{
p→next=head;
head→prev=p;
p→prev=NULL;
head=p;
}
return (head);
}
By Nitin Sir
91 | R K D E M Y
Insert at end
By Nitin Sir
92 | R K D E M Y
P→data=x;
If(head==NULL)
{
head=p;
head→next=head→prev=NULL;
}
else
{
q=head;
While(q→next!=NULL)
{
q=q→next;
}
q→next=p;
p→prev=q;
p→next=NULL;
}
return(head);
}
By Nitin Sir
93 | R K D E M Y
Deletion of a node
By Nitin Sir
94 | R K D E M Y
#include<stdio.h>
#include<conio.h>
typedef struct dnode
{
Int data;
struct dnode *next, *prev;
}dnode;
dnode* create();
dnode* insert_b(dnode * head, intX);
dnode* insert_e(dnode * head, intx);
dnode* delete(dnode * head);
void print(dnode* head);
void main()
{
int op, x;
dnode * head=null;
do
{
printf(“1-create\n 2-insert in beginning \n 3-Insert at end\n 4-
delete a specific\n 5-display\n 6-quit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&top);
switch(op)
{
case1:
head=create();
break;
case2:
printf(“enter the data to be inserted\n);
By Nitin Sir
95 | R K D E M Y
scanf(“%d”,&x);
Head=insert_b(head, x);
break;
case3:
printf(“enter data to be inserted\n”);
scanf(“%d”,&x);
head=insert_e(head, x);
break;
case4:
printf(“enter the data to be deleted\n”);
scanf(“%d”,&x);
head=delete(head,x);
break;
case5:
print(head);
break;
default:
}
}while(op!=6);
getch();
}
void create ()
{
dnode *head, *p;
int n, x, i;
printf(“ Enter no of items”);
scanf(“%d”, &n);
head=(dnode*)malloc(sizeof(dnode));
//read the data in 1st node
scanf(“%d”, &(head->data));
head->next=head;
p=head;
for(i=1;i<n;i++)
{
p->next=(node*)malloc(sizeof(node));
p=p->next;
p->next=head;
scanf(“%d”, &(p->data));
}
By Nitin Sir
96 | R K D E M Y
Initilize a stack
stack *P;
P→data= X;
P→next= *T;
*T= P;
By Nitin Sir
97 | R K D E M Y
Int x;
Stack *p;
P= *T;
*T= P→next;
x= P→data;
free(p);
return (X);
if (Top= = Null)
{
return (1);
}
else
{
return (0);
}
}
# include<stdio.h>
#include<conio.h>
typedef struct stack
{
char data;
struct stack *next;
}
By Nitin Sir
98 | R K D E M Y
void main()
{
Stack *top;
char x;
init(&top);
printf(“enter the spring\n”)
While ((x=getchar())!=’\n’)
{
Push(&top, x);
}
while(!empty (top))
{
x =pop(&top);
printf(“%c”, x);
}
void init(stack**T)
{
*T=NULL;
}
Int empty (stack *top)
{
If(top= = NULL)
return(1);
return(0);
}
void push(stack**T, char x)
{
stack *p;
p=(stack*)malloc(sizeof(stack));
P→data= x;
By Nitin Sir
99 | R K D E M Y
P→next= *T;
*T=P;
}
char pop (stack**T)
{
char x;
Stack *P;
P=*T;
*T= P→next;
X= P→data;
free(p);
return(x);
}
Write a program, for various operations on queue using circular linked list.
#include<stdio.h>
#include<conio.h>
typedef struct node
{
int data;
struct node*next;
}node;
Void int(node **R);
Void enqueuer(node **R,int x);
Int dequeue(node **R);
Int empty(node **R);
Void print(node **R);
Void main()
{
Int x,ch;
Int n=0,i;
node *rear;
By Nitin Sir
100 | R K D E M Y
init(&rear);
do
{
Printf(“1.Insert\n2.deletion\3.print\n4.Quit”);
Printf(“Enter your option\n’);
Scanf(“%d”,&ch);
Switch(ch)
{
Case 1:
Printf (“Nuumber of elements to be inserted”);
Scanf(“%d”,&n);
For (!=0;1<n;!++)
{
Scanf(“%d”,&X);
Enqueue (&rear,X);
}
Break;
Case 2:
If(!empty(&rear))
{
X= dequeuer(&rear);
Printf(“\element delete=%d”,x);
}
Else
{
Printf(“underflow…”);
}
Break;
Case 3:
Print(&rear);
Break;
Default:
}
}while(ch!=4);
getch();
}
Void enqueuer(node**R, intX)
{
node*P;
By Nitin Sir
101 | R K D E M Y
P→data=X;
If(empty(*R))
{
P→next=p;
*R=P;
}
else
{
P→next=(*R)→next;
(*R)→next)=P;
*R=P;
}
}
Int dequeue (node**R)
{
Int X;
node*P;
P=(*R)→next;
P→data=x;
If(P→next==P)
{
*R=NULL;
free(p);
return(X);
}
(*R)→next= P→next;
Free(P);
Return(X);
}
Void print(node*rear)
{
node*P;
If (!empty(rear))
{
P=rear→next;
While(P!=rear)
{
Printf(“%d”,P→data);
P=P→next;
}
Printf(”%d”,P→data);
}
By Nitin Sir
102 | R K D E M Y
}
Int empty(node*P)
{
If (P→nexrt=== -1)
{
return(1);
}
return(0);
}
Important Questions
• Write a c program to implement singly list which supports the
following operation.
• Insert node in the beginning.
• Insert a node in the end
• Insert a node after a specific node.
• Deleting a specific node.
• Displaying the list.
• State difference between singly and doubly linked list along with
application.
• What is circular queue? Write a program in c to implement it. [M-10
May-2015]
• Write a c program in ‘C’ to implement doubly link-list with methods
insert, delete and search. [M-10 May-14]
• What is linked list and explain its types [3M May-18]
• Insert the following elements in AVL tree 44,17,32,78,50,88,48,62,54
explain different types of rotations that can be used. [10M May-18]
• Explain different types of tree traversal techniques with example, also
write recursive function for each traversal technique. [10M May-18]
• Write a function in c to implement binary search [5M Dec-18]
• What are expression trees ? what are its advantages ? Derive the
expression tree for following algebraic expression ?
(a + (b/c) )*((d/e)-f) [8M DEC-18]
By Nitin Sir
103 | R K D E M Y
• Write a short not on AVL tree and expression tree [10M DEC-17]
• Explain AVL tree, Insert the following elements in AVL search tree
63, 52,49,83, 92, 29, 23, 54, 13, 99 [10M DEC-17]
• Explain Threaded Binary Tree [5M DEC-17]
• Describe expression Tree with example
• Write a program in c to delete a node from a Binary search tree. The
program should consider the all the possible cases.
• IT
What is linked list? State its advantage, Explain its types [3M DEC-18,
May-18]
• Define minimum spanning tree. List techniques to compute minimum
spanning tree. [3M May-18]
• Define expression tree with example. [3M DEC-18, May-18]
• Write an algorithm to create doubly linked list and display it [10M
May-18]
• Define binary search tree ? Explain different operation on binary
search tree with example. [10M May-18]
• Define binary search tree ? find inorder, preorder and postorder of
following binary tree. [10M DEC-18]
•
• Define binary search tree ? write an algorithm for following operation
• Insertion
• Deletion
• What is minimum spanning tree? Draw MST using kruskal’s and prims
algorithm. [10M May-18]
• What is minimum spanning tree? Explain kruskal’s algorithm with an
example. [10M May-18]
By Nitin Sir
104 | R K D E M Y
• Explain binary search tree. Construct binary search tree for following
elements 47,12,75, 88, 90, 73, 57, 1, 85, 50, 62 [10M DEC-18]
Algorithm
Queue is Full
begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
endif
end procedure
Queue is Empty
begin procedure isempty
end procedure
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Insert Operation
By Nitin Sir
105 | R K D E M Y
TREE
Introduction to Trees
A tree is a collection of elements called “nodes”,one of which is distinguished
as a root say r ,
The root can have zero or more nonempty subtrees T1 , T2 ,… Tk each of whose
roots are connected by a directed edge from r.
Root: it is a special node in a tree structure and the entire tree is referenced
through it. This mode does not have a parent.
Child: All immediate successor of a node are its children. In the fig B,C and D
are the children of A.
Siblings: nodes with the same parent are siblings H,I and J are siblings as
they are children of the same parent D.
Path: it is number of successive edges from source node to destination node.
Degree of a node:
The degree of a node is a number of children of a node
By Nitin Sir
106 | R K D E M Y
Leaf node: A node of degree 0 is also know as a leaf node. A leaf node is a
terminal node and it has no children.
Depth: The Depth of a binary tree is the maximum level of any node in the
tree. This is equal to the node in the tree. This is equal to the longest path
from the root to any leaf node.
Binary Tree
A tree is binary if each node of the tree can have maximum of two children.
Children of a node of binary tree are ordered. One child is called the “left”
child and the other is called “right” child.
By Nitin Sir
107 | R K D E M Y
By Nitin Sir
108 | R K D E M Y
By Nitin Sir
109 | R K D E M Y
By Nitin Sir
110 | R K D E M Y
if (T!=NULL)
inorder (T→left);
printf(‘\n%, T→data);
if(T!= NULL)
By Nitin Sir
111 | R K D E M Y
postorder(T→left);
postorder (T→right);
print (“\n%d”,T→data);
Preorder sequence : A B C D E F G H I J
Inorder sequence : D C E B G F A I H J
Postorder sequence : D E C G F B I J H A
2. For the given binary tree, perform inorder, preorder and postorder
traversal.
By Nitin Sir
112 | R K D E M Y
Postorder sequence : A B D G K H L M C E
Inorder sequence : K G D L H M A E C
Preorder sequence : K G L M H D B E C A
By Nitin Sir
113 | R K D E M Y
Preorder A B D G C E H I F
Inorder D G B A H E I C F
Step 1 :
A
DGB HEICF
Step 2 :
A
B C
DG F
HE
I
Step 3 :
C
B
D F
E
F H I
By Nitin Sir
114 | R K D E M Y
A binary search tree is a binary tree, which is either empty or in which each
node contains a key that satisfies the following conditions
The basic operations that can be performed on a binary search tree data
structure, are the following −
Find Operation
Whenever an element is to be searched, start searching from the root node,
then if the data is less than the key value, search for the element in the left
subtree. Otherwise, search for the element in the right subtree.
Recursive
BSTnode * Find(BSTnode *root, int x)
{
if (root == NULL )
{
return(null);
}
By Nitin Sir
115 | R K D E M Y
if(root→data == x)
return root;
if (root->key < key)
return search(root→right, x);
else
return search(root→left, x);
}
Non recursive
BSTnode * Find(BSTnode *root, int x)
{
while(root != null)
{
If(x==root→data)
return (root);
if(x>root→data)
root=root->right;
else
root=root→left;
}
return(NULL);
}
Insert Operation
The very first insertion creates the tree. Afterwards, whenever an element is
to be inserted, first locate its proper location. Start searching from the root
node, then if the data is less than the key value, search for the empty location
in the left subtree and insert the data. Otherwise, search for the empty
location in the right subtree and insert the data.
By Nitin Sir
116 | R K D E M Y
T->data = x;
return temp;
}
/* Otherwise, recur down the tree */
if (X <T->data)
T->left = insert(T->left, X);
else if (X> T->key)
T->right = insert(T->right, key);
return (T);
}
Delete Operation
1. A Leaf node
2. A node with one child.
3. A node with two child.
By Nitin Sir
117 | R K D E M Y
1. A Leaf node
If node q is to be deleted and it is right child of its parent node p. the only
child of q will become the right child of p after deletion of q.
By Nitin Sir
118 | R K D E M Y
//One Child
if(root->left ==NULL || root->right ==NULL)
{
By Nitin Sir
119 | R K D E M Y
BSTnode *temp;
if(root->left ==NULL)
temp = root->right;
else
temp = root->left;
free(root);
return temp;
}
//Two Children
else
{
By Nitin Sir
120 | R K D E M Y
30,100,90,15,2,25,36,72,78,10
By Nitin Sir
121 | R K D E M Y
In linked representation of tree, there are more number When a binary tree
is represented using linked list representation.
If any node is not having a child we use a NULL pointer. These special
pointers are threaded and the binary tree having such pointers is called a
threaded binary tree.
This NULL pointer does not play any role except indicating there is no child.
Double Threaded: Where both left and right NULL pointers are made to
point to inorder predecessor and inorder successor respectively. The
predecessor threads are useful for reverse inorder traversal and postorder
traversal.
The threads are also useful for fast accessing ancestors of a node.
• Binary trees have a lot of wasted space: the leaf nodes each have 2 null
pointers. We can use these pointers to help us in inorder traversals.
• Threaded binary tree makes the tree traversal faster since we do not
need stack or recursion for traversal
By Nitin Sir
122 | R K D E M Y
Huffman Coding
A text message can be converted into a sequence of 0’s and 1’s by replacing
each character of the message with its code.
It uses variable length encoding where variable length codes are assigned to
all the characters depending on how frequently they occur in the given text.
The character which occurs most frequently gets the smallest code and the
character which occurs least frequently gets the largest code.
Huffman’s algorithm
Characters Frequencies
A 10
E 15
I 12
O 3
U 4
By Nitin Sir
123 | R K D E M Y
S 13
t 1
Solution-
First let us construct the Huffman tree using the steps we have learnt above-
Step-01:
Step-02:
Step-03:
Step-04:
By Nitin Sir
124 | R K D E M Y
Step-05:
By Nitin Sir
125 | R K D E M Y
Step-06:
Step 7
By Nitin Sir
126 | R K D E M Y
By Nitin Sir
127 | R K D E M Y
After we have constructed the Huffman tree, we will assign weights to all the edges. Let us assign
weight ‘0’ to the left edges and weight ‘1’ to the right edges
We will traverse the Huffman tree from the root node to all the leaf nodes
one by one and and will write the Huffman code for all the characters-
• a = 111
• e = 10
• i = 00
• o = 11001
• u = 1101
• s = 01
• t = 11000
By Nitin Sir
128 | R K D E M Y
= 2.52
= 58 x 2.52
= 146.16
AVL TREE
Adelson, Velski & Landis, AVL trees are height balancing binary search
tree. AVL tree checks the height of the left and the right sub-trees and
assures that the difference is not more than 1. This difference is called the
Balance Factor.
BalanceFactor=height(leftsutree)−height(right sutree)
If the difference in the height of left and right sub-trees is more than 1, the
tree is balanced using some rotation techniques.
AVL Rotations
To balance itself, an AVL tree may perform the following four kinds of
rotations −
• Left rotation
• Right rotation
• Left-Right rotation
• Right-Left rotation
By Nitin Sir
129 | R K D E M Y
The first two rotations are single rotations and the next two rotations are
double rotations. To have an unbalanced tree, we at least need a tree of
height 2. With this simple tree, let's understand them one by one.
Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree
of the right subtree, then we perform a single left rotation −
Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of
the left subtree. The tree then needs a right rotation.
As depicted, the unbalanced node becomes the right child of its left child by performing a
right rotation.
Left-Right Rotation
State Action
By Nitin Sir
130 | R K D E M Y
A node has been inserted into the right subtree of the left subtree.
This makes C an unbalanced node. These scenarios cause AVL tree
to perform left-right rotation.
We shall now right-rotate the tree, making B the new root node of
this subtree. C now becomes the right subtree of its own left
subtree.
Right-Left Rotation
By Nitin Sir
131 | R K D E M Y
State Action
A node has been inserted into the left subtree of the right subtree.
This makes A, an unbalanced node with balance factor 2.
By Nitin Sir
132 | R K D E M Y
Expression tree
A+B*C+D*E
By Nitin Sir
133 | R K D E M Y
B-Trees
The B-tree is a generalization of a binary search tree in that a node can have
more than two children.
When large volume of data is handled, the search tree can not
accommodated in primary, b tree primarily meant for secondary storage.
B-Tree is a M-way tree. And M-way tree can have maximum of M children.
Properties of B-Tree
By Nitin Sir
134 | R K D E M Y
2. All nodes except root must have at least [m/2]-1 keys and maximum
of m-1 keys.
3. All non leaf nodes except root (i.e. all internal nodes) must have at
least m/2 children.
4. If the root node is a non leaf node, then it must have atleast 2 children.
5. A non leaf node with n-1 keys must have n number of children.
6. All the key values in a node must be in Ascending Order.
By Nitin Sir
135 | R K D E M Y
GRAPHS
A graph G is a set of vertices (V) and set of edges (E)
G=(V,E)
V(G)=Vertices of graph G
E(G)=Edges of graph G
V(𝐺1 )={A,B,C,D,E,F}
Types of Graph
1. Undirected Graph
A graph containing unordered pair of vertices is called an undirected
graph.
In an undirected graph, pair of vertices (1,0) and (0,1)represent the
same edge.
2. Directed Graph
A graph containing ordered pair of vertices is called a direct graph.
By Nitin Sir
136 | R K D E M Y
3. Complete Graph
An undirected graph, in which every vertex has an edge to all other
vertices is called a complete graph.
4. Weighted Graph
A weighted graph is a graph in which edges are assigned some value.
Most of the physical situation shown using weighted graph.
A weighted graph is a graph in which edges are assigned some value.
The weight will denote the distance between two connected cities
using highway
By Nitin Sir
137 | R K D E M Y
Cycle
A cycle is a simple path that begins and ends at the same vertex.
Cost : The cost of a graph is the sum of the cost of the edges in the weighted
graph.
TREE
Degree of Vertex:-
The outdegree of a node is the total number of edges going out from
that node.
By Nitin Sir
138 | R K D E M Y
Spanning tree
The cost of the spanning tree is the sum of the weights of all the edges in the
tree. There can be many spanning trees.
Minimum spanning tree is the spanning tree where the cost is minimum
among all the spanning trees. There also can be many minimum spanning
trees.
By Nitin Sir
139 | R K D E M Y
Representation of graphs
1. Adjacency matrix
A two dimensional matrix can be used to store a graph.
A graph is represented using a square matrix.
By Nitin Sir
140 | R K D E M Y
Adjacency List
A graph can be represented using a linked list For each vertex a list of
adjacent vertices is maintained using a linked list.
When we traverse all the adjacent nodes, we set the next pointer to
null at the end of the list.
By Nitin Sir
141 | R K D E M Y
Traversal of graph
By Nitin Sir
142 | R K D E M Y
Algorithm
By Nitin Sir
143 | R K D E M Y
{
scanf("%d",&G[i][j]);
}
}
//visited is initialized to zero
for(i=0;i<n;i++)
{
visited[i]=0;
}
DFS(0);
}
void DFS(int i)
{
int j;
printf("%d",i);
visited[i]=1;
for(j=0;j<n;j++)
{
if(!visited[j] && G[i][j]==1)
{
DFS(j);
}
}
}
By Nitin Sir
144 | R K D E M Y
• The algorithm for BFS has to maintain a list of vertices which have
been visited but not explored for adjacent vertices.
• The vertices which have been visited but not explored for adjacent
vertices can be stored in queue.
• In every iteration, a vertex is removed from the queue and its adjacent
vertices which are not visited as yet are added to the queue.
By Nitin Sir
145 | R K D E M Y
Algorithm
1. Initialize all the vertex.
2. Initialize array of visited [ ] to false (0)
3. Enqueue starting vertex in queue.
4. Mark it as visited [ ] to true (1)
5. Dequeue from queue.
6. Add to rear of queue all neighbors of deleted node that are not
visited.
7. If queue is not empty go to step5.
8. End.
#include<stdio.h>
#include<conio.h>
typedef struct Queue
{
Int data[max];
Int F,R;
}Queue;
Void enqueue(Queue *q,int x);
Void Init(Queue *q);
int dequeue(Queue *q);
int empty((Queue *q);
void BFS(int);
By Nitin Sir
146 | R K D E M Y
int G[10][10];
int visited[10],n; //n is no of vertices and graph is sorted in array
void main()
{
int i,j,v;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&G[i][j]);
}
}
//visited is initialized to zero
for(i=0;i<n;i++)
{
visited[i]=0;
}
Printf(“Enter the starting vertex\n”);
Scanf(“%d”,&v);
BFS(v);
getch();
}
Void BFS(int v)
{
Queue q;
Init(&q);
Enqueue(&q, v);
printf(“%d”, v);
visited [v]=1;
while(!empty(&q))
{
V=dequeue(&q);
For ( i=0 ; i<n ; i++)
By Nitin Sir
147 | R K D E M Y
{
If(visited[i]==0 && G[V][i]==1)
{
enqueue( &q, i);
visited[i]=1;
printf(“%d”,i);
}
}
}
}
Important questions
What is graph explain methods to represent graph [May, DEC-18 5M]
Define graph? List the types of graph with example? [3M DEC-18]
What is minimal spanning tree ? Draw MST using kruskal’s and prims
algorithm and find out cost. [10M DEC-18]
By Nitin Sir
148 | R K D E M Y
1. Internal sorting
2. External sorting
1. Internal sorting
Internal sorting takes place in the main memory of the computer.
2. External sorting
External sorting is carried on secondary storage.
Sorting Efficiency
1. Best case
2. Worst case
3. Average case
Most of the primitive sorting algorithms like bubble sort, selection sort and
insertion sort are not suited for sorting a large files.
Advance sorting algorithms like quick sort, merge sort and heap sort have a
timing requirement of 𝑂(𝑛 𝑙𝑜𝑔𝑛).
By Nitin Sir
149 | R K D E M Y
Bubble Sort
Bubble sort is one of the simplest and the most popular sorting method.
The basic idea behind bubble sort is as a bubble rises up in water, the
smallest element goes to beginning.
j=0 5 9 6 2 8 1
j=1 5 9 6 2 8 1
j=2 5 6 9 2 8 1
j=3 5 6 2 9 8 1
j=4 5 6 2 8 9 1
j=0 5 6 2 8 1 9
`j = 1 5 6 2 8 1 9
j=2 5 2 6 8 1 9
j=3 5 2 6 8 1 9
j=0 5 2 6 1 8 9
j=1 2 5 6 1 8 9
j=2 2 5 6 1 8 9
j=0 2 5 1 6 8 9
By Nitin Sir
150 | R K D E M Y
j=1 2 5 1 6 8 9
Fifth pass i= 5
j=0 2 1 5 6 8 9
By Nitin Sir
151 | R K D E M Y
getch();
}
void bubble_sort(int a[ ],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a(j);
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
Selection Sort
Selection sort is very simple sorting method.
5 9 1 11 2 4 Original array
By Nitin Sir
152 | R K D E M Y
By Nitin Sir
153 | R K D E M Y
{
k=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[k])
{
k=j;
}
}
if(k!=i)
{
temp=a[i];
a[i]=a[k];
a[k]=temp;
}
}
Insertion Sort
An element can always be placed at a right place in sorted list of element
Insertion sort is based on the principle of inserting the element at its
correct place in a previously sorted list. I can be varied 1 to n-1 to sort the
entire array.
By Nitin Sir
154 | R K D E M Y
By Nitin Sir
155 | R K D E M Y
getch();
}
void insertion_sort(int a[], int n)
{
int I, j, temp;
for(i=1;i<n;i++)
{
temp=a[i];
for(j=i-1; j>=0 && a[j]>temp; j--)
{
a[j+1]=a[j];
}
a[j+1]=Temp;
}
}
Quick Sort
Quick sort is the fastes internal sorting algorithm with the time complexity=
O(n log n ).
By Nitin Sir
156 | R K D E M Y
By Nitin Sir
157 | R K D E M Y
j=u+1;
do
{
do
{
i++;
}while(a[i]<v && i<=u);
do
{
j--;
}while(a[j]>v);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return (j);
}
By Nitin Sir
158 | R K D E M Y
Merge sort
Merge sort runs in O(N Log N ) running time. It is a very efficient sorting
algorithm with near optimal number of comparisons
Basic operation in merge sort is that of merging of two sorted list into one
sorted list. Merging operation has a liner time complex
Advantages and Disadvantages of Merge sort:
Advantages
1. It has a timing complexity of O(n log n).
2. It can be used both for internal as well as external sorting.
3. It is a stable sorting algorithm.
By Nitin Sir
159 | R K D E M Y
Disadvantages
By Nitin Sir
160 | R K D E M Y
If(a[i]<a[j])
{
c[k]=a[i];
k++; i++;
}
else
{
c[k]=a[j];
k++; j++;
}
}
while (i<=m)
{
c[k]=a[i];
k++; i++;
}
while(j<=u)
{
c[k]=a[j];
k++; j++;
}
for(i=l,j=0;i<=u;i++,j++)
{
a[i]=c[j];
}
}
By Nitin Sir
161 | R K D E M Y
By Nitin Sir
162 | R K D E M Y
Radix sort
Radix sort is generalization of bucket sort. To sort decimal numbers, where
the redix or base is 10, we need 10 buckets . These buckets are numbered
0,1,2,3,4,5,6,7,8,9. Sorting is done in passes
Number of passes required to sort using shell sort is equal to number of
digits in the largest number in the list
Range Passes
0to 99 2 passes
0to999 3 passes
0to9999 4 passes
In the first pass, number are sorted on least significant digit. Numbers with
the same least significant digit are sorted in the same bucket
• In the 2nd pass, numbers are sorted on the second least significant
digit.
By Nitin Sir
163 | R K D E M Y
By Nitin Sir
164 | R K D E M Y
Heap sort
Heap sort is one of the sorting algorithms used to arrange a list of elements
in order.
Heapsort algorithm uses one of the tree concepts called Heap Tree.
Step 3 - Delete the root element from Min Heap using Heapify method.
By Nitin Sir
165 | R K D E M Y
By Nitin Sir
166 | R K D E M Y
By Nitin Sir
167 | R K D E M Y
Searching
Searching is a technique of finding an element in a given list
of elements
Searching technique should be able to locate the element to
be searched as quickly as possible.
The complexity of any searching algorithm depends on
number of comparisons required to find the element.
Performance of searching algorithm can be found by
counting the number of comparisons in order to find the
given element.
By Nitin Sir
168 | R K D E M Y
if(a[i]==key)
{
return (i);
}
i++;
}
return (-1);
}
Write a program for sequential search
#include <conio.h>
#include<stdio.h>
void sequential_search(int[ ],int);
void main()
{
int a[50],n, i;
printf(“\nEnter no of elements :”);
scanf(“%d”,&n);
printf(“\nEnter array elements :”);
for(i=0;i<n;i++)
scanf (“%d”,&a[i]);
printf(“Element to be search \n”);
scanf(“%d”, &key);
if(i==-1)
By Nitin Sir
169 | R K D E M Y
{
Printf(“Not found \n”);
}
Else
{
Printf(“Found at location %d”, i+1);
}
getch();
}
Binary Search
Binary search exhibits much better timing behavior in case of large volume
of data.
Algorithm
By Nitin Sir
170 | R K D E M Y
By Nitin Sir
171 | R K D E M Y
If(i<=j)
Return c;
Return (-1);
return (i);
}
i++;
}
return (-1);
}
What is Hashing
Hashing is a technique that is used to uniquely identify a specific object from a group of similar
objects. Some examples of how hashing is used in our lives include:
• In universities, each student is assigned a unique roll number that can be used to
retrieve information about them.
• In libraries, each book is assigned a unique number that can be used to determine
information about the book, such as its exact position in the library or the users it has
been issued to etc.
In both these examples the students and books were hashed to a unique number.
Assume that you have an object and you want to assign a key to it to make searching easy. To
store the key/value pair, you can use a simple array like a data structure where keys (integers)
can be used directly as an index to store values. However, in cases where the keys are large and
cannot be used directly as an index, you should use hashing.
In hashing, large keys are converted into small keys by using hash functions.
The values are then stored in a data structure called hash table.
The idea of hashing is to distribute entries (key/value pairs) uniformly across an array.
Each element is assigned a key (converted key). By using that key you can access the element
in O(1) time. Using the key, the algorithm (hash function) computes an index that suggests
where an entry can be found or inserted.
By Nitin Sir
172 | R K D E M Y
1. An element is converted into an integer by using a hash function. This element can be
used as an index to store the original element, which falls into the hash table.
2. The element is stored in the hash table where it can be quickly retrieved using hashed
key.
hash = hashfunc(key)
index = hash % array_size
In this method, the hash is independent of the array size and it is then reduced to an index (a
number between 0 and array_size − 1) by using the modulo operator (%).
• Suppose we have integer items {26, 70, 18, 31, 54, 93}. One common method of
determining a hash key is the division method of hashing and the formula is :
Hash Key = Key Value % Number of Slots in the Table
• Division method or reminder method takes an item and divides it by the table size and
returns the remainder as its hash value.
Data Item Value % No. of Slots Hash Value
26 26 % 10 = 6 6
70 70 % 10 = 0 0
18 18 % 10 = 8 8
31 31 % 10 = 1 1
54 54 % 10 = 4 4
93 93 % 10 = 3 3
Hash function
To achieve a good hashing mechanism, It is important to have a good hash function with the
following basic requirements:
1. Easy to compute: It should be easy to compute and must not become an algorithm in
itself.
2. Uniform distribution: It should provide a uniform distribution across the hash table and
should not result in clustering.
3. Less collisions: Collisions occur when pairs of elements are mapped to the same hash
value. These should be avoided.
Note: Irrespective of how good a hash function is, collisions are bound to occur.
Therefore, to maintain the performance of a hash table, it is important to manage
collisions through various collision resolution techniques.
The hash function will compute the same index for all the strings and the strings will be stored
in the hash table in the following format. As the index of all the strings is the same, you can
create a list on that index and insert all the strings in that list.
Hash table
A hash table is a data structure that is used to store keys/value pairs. It uses a hash function to
By Nitin Sir
173 | R K D E M Y
compute an index into an array in which an element will be inserted or searched. By using a
good hash function, hashing can work well. Under reasonable assumptions, the average time
required to search for an element in a hash table is O(1).
Separate chaining is one of the most commonly used collision resolution techniques. It is
usually implemented using linked lists. In separate chaining, each element of the hash table is a
linked list. To store an element in the hash table you must insert it into a specific linked list. If
there is any collision (i.e. two different elements have same hash value) then store both the
elements in the same linked list.
The cost of a lookup is that of scanning the entries of the selected linked list for the required
key. If the distribution of the keys is sufficiently uniform, then the average cost of a lookup
depends only on the average number of keys per linked list. For this reason, chained hash tables
remain effective even when the number of table entries (N) is much higher than the number of
slots.
For separate chaining, the worst-case scenario is when all the entries are inserted into the same
linked list. The lookup procedure may have to scan all its entries, so the worst-case cost is
proportional to the number (N) of entries in the table.
In open addressing, instead of in linked lists, all entry records are stored in the array itself.
When a new entry has to be inserted, the hash index of the hashed value is computed and then
the array is examined (starting with the hashed index). If the slot at the hashed index is
By Nitin Sir
174 | R K D E M Y
unoccupied, then the entry record is inserted in slot at the hashed index else it proceeds in some
probe sequence until it finds an unoccupied slot.
The probe sequence is the sequence that is followed while traversing through entries. In
different probe sequences, you can have different intervals between successive entry slots or
probes.
When searching for an entry, the array is scanned in the same sequence until either the target
element is found or an unused slot is found. This indicates that there is no such key in the table.
The name "open addressing" refers to the fact that the location or address of the item is not
determined by its hash value.
Linear probing is when the interval between successive probes is fixed (usually to 1). Let’s
assume that the hashed index for a particular entry is index. The probing sequence for linear
probing will be:
Quadratic Probing
Quadratic probing is similar to linear probing and the only difference is the interval between
successive probes or entry slots. Here, when the slot at a hashed index for an entry record is
already occupied, you must start traversing until you find an unoccupied slot. The interval
between slots is computed by adding the successive value of an arbitrary polynomial in the
original hashed index.
Let us assume that the hashed index for an entry is index and at index there is an occupied slot.
The probe sequence will be as follows:
By Nitin Sir