data structure in c programming language
TRANSCRIPT
ARKADEEP DEY (CSE2015/030) CS392
1
ArrAy
Q-1> Program for creation of array and insertion of element in the array.
#include<stdio.h>
main()
{
int array[100], position, c, n, value; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter %d elements\n", n); for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n"); scanf("%d", &position); printf("Enter the value to insert\n"); scanf("%d", &value); for ( c = n - 1 ; c >= position - 1 ; c-- )
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for( c = 0 ; c <= n ; c++ )
printf("%d\n", array[c]);
return 0;
}
ARKADEEP DEY (CSE2015/030) CS392
2
Q-2>.Program for creation of array and deletion of element in the array.
#include<stdio.h> main() {
int array[100], position, c, n; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter %d elements\n", n); for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Enter the location where you wish to delete element\n"); scanf("%d", &position); if ( position >= n+1 )
ARKADEEP DEY (CSE2015/030) CS392
3
printf("Deletion not possible.\n");
else
{
for ( c = position - 1 ; c < n - 1 ; c++ )
array[c] = array[c+1];
printf("Resultant array is\n");
for( c = 0 ; c < n - 1 ; c++ )
printf("%d\n", array[c]);
}
return 0;
}
Q-3.Program for creation of 1D array dynamically.
#include <stdio.h> #include <stdlib.h>
int main()
{
ARKADEEP DEY (CSE2015/030) CS392
4
int num, i, *ptr;
printf("\nEnter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("\n\nEnter elements of array:\n");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
}
printf("\nThe Dynamically created array is:");
for(i = 0; i < num; ++i)
printf("\n%d", ptr[i]);
free(ptr);
return 0;
}
ARKADEEP DEY (CSE2015/030) CS392
5
Q-4 > Creation of 2D array dynamically.
#include<stdio.h> #include<conio.h> #include<malloc.h> void dynamic_array (int**,int,int); void display(int**,int,int); int main() {
int **a,row,column; printf("\n enter how many row:"); scanf("%d",& row); a=(int **)malloc(sizeof(int)*row); printf("\n how many column:"); scanf("%d",&column); dynamic_array(a,row,column); display(a,row,column); getch(); return 0;
} void dynamic_array(int **a,int row,int column) {
int i,j; for(i=0;i<row;i++) {
ARKADEEP DEY (CSE2015/030) CS392
6
a[i]=(int*)malloc(sizeof(int)*column); } for(i=0;i<row;i++)
{ for(j=0;j<column;j++) { printf("a[%d][%d]=",i+1,j+1); scanf("%d",&a[i][j]); }
} } void display(int **a,int row,int column) {
int i,j; printf("\n the array elements are:\n"); for(i=0;i<row;i++) {
for(j=0;j<column;j++) {
printf("a[%d][%d]=%d\t",i+1,j+1,a[i][j]); } printf("\n");
} }
Q-5>Creation of shortcut of sparce matrix . #include<stdio.h> #include<conio.h>
ARKADEEP DEY (CSE2015/030) CS392
7
#define MAXROW 10 #define MAXCOL 10 int sparse[MAXROW][MAXCOL]; int vector[30][3]; void sparsematrix(int,int); void generate_vector(int,int); int main () { int r,c,i,j; printf("\n\tEnter The no.of rows:"); scanf("%d",&r); if(r>MAXROW) { printf("\n\tNomber of rows should be <=10"); exit(0); } printf ("\n\tEnter the no.of cols:"); scanf("%d",&c); if(c>MAXCOL) { printf("\n\tNo. of cols. should be<=10"); exit(0); } sparsematrix(r,c); getch(); return 0; } void sparsematrix(int r,int c) { int i,j; printf ("\n\tEnter the elements->"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("\n\telement:->"); fflush(stdin); scanf("%d",&sparse[i][j]);
ARKADEEP DEY (CSE2015/030) CS392
8
} } generate_vector(r,c); } /*FOR CHANGING THE MATRIX*/ void generate_vector(int r,int c) { int i,j,p=1; /*Scaning the sparse matrix*/ for(i=0;i<r;i++) { for(j=0;j<c;j++) { if(sparse[i][j]!=0) { vector[p][0]=i; vector[p][1]=j; vector[p][2]=sparse[i][j]; p++; } } } /*Filling the header information*/ vector[0][0]=r; vector[0][1]=c; vector[0][2]=p-1; printf("\n\tRow Col value"); /*Printing the vector representation*/ for(i=0;i<p;i++) printf("\n\t%d\t%d\t%d",vector[i][0],vector[i][1],vector[i][2]); }
ARKADEEP DEY (CSE2015/030) CS392
9
recursion
Q-6>factorial using recursion:
#include<stdio.h> #include<conio.h> long int fact(int); int main() { int n; long int c; printf("\n enter the number(must be positive integer):"); scanf("%d",&n); c=fact(n); printf("\n the factorial of %d no is->%ld",n,c); getch(); return 0; } long int fact(int n) { if(n==0) return 1; else if(n==1) return n; else return n*fact(n-1); }
Q-7>Gcd using recursion:
#include<stdio.h>
#include<conio.h>
int gcd(int,int);
ARKADEEP DEY (CSE2015/030) CS392
10
int main()
{
int a,b,c;
printf("\n enter two number:");
scanf(" %d %d",&a,&b);
c=gcd(a,b);
printf("\n the gcd of %d and %d is->%d",a,b,c);
getch();
return 0;
}
int gcd(int a,int b)
{
if(a<b)
gcd(b,a);
if(a%b==0)
return b;
else
return gcd(b,a%b);
}
Q-8> Program to generate Fibonacci series using recursion.
ARKADEEP DEY (CSE2015/030) CS392
11
#include<stdio.h>
void printFibonacci(int);
int main(){
int k,n; long int i=0,j=1,f; printf("\nEnter the range of the Fibonacci series: \n"); scanf("%d",&n); printf("\nFibonacci Series: \t"); printf("%d %d ",0,1); printFibonacci(n); return 0; }
void printFibonacci(int n){
static long int first=0,second=1,sum; if(n>0){ sum = first + second; first = second; second = sum; printf("%ld ",sum); printFibonacci(n-1); } }
ARKADEEP DEY (CSE2015/030) CS392
12
Q-9>tower of hanoi using recursion:
#include<stdio.h>
#include<conio.h>
void toh(char,char,char,int);
int main()
{ char a='a',b='b',c='c';
int n;
printf("\n enter the number of discs:");
scanf("%d",&n);
toh(a,b,c,n);
getch();
return 0;
}
void toh(char a,char b,char c,int n)
{
if(n==1)
printf("\n move disk form %c->%c",a,c);
else
{
toh(a,c,b,n-1);
toh(a,b,c,1);
toh(b,a,c,n-1);
} }
ARKADEEP DEY (CSE2015/030) CS392
13
single link list
Q-10>a>singly link list create , display , count:
#include <stdio.h> #include <conio.h> #include <malloc.h>
typedef struct list{
int data;
list *link;
} list;
list *head;
void display(list*);
list* append(list*);
int count(list*);
int main()
{
int p,k;
list *d;
d=(list*)malloc(sizeof(list));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
ARKADEEP DEY (CSE2015/030) CS392
14
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
printf("The no.of nodes = %d",count(head));
scanf("%d",&p);
return 0;
}
list* append(list *l){
char c;
list *node;
node=(list*)malloc(sizeof(list));
printf("Enter the data :");
scanf("%d",&node->data);
node->link=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->link=node;
l=node ;
}
return(l);
ARKADEEP DEY (CSE2015/030) CS392
15
}
void display(list *h){
while(h!=NULL){
printf("%d -> ",h->data);
h=h->link;
}
printf("NULL\n");
printf("----------------------------------------------\n");
}
int count(list *h){
int c=0;
while(h!=NULL){
c++;
h=h->link;
}
return c;
}
Q-10>b>reverse of a singly link list:
#include <stdio.h>
#include <conio.h>
ARKADEEP DEY (CSE2015/030) CS392
16
#include <malloc.h>
typedef struct list{
int data;
list *link;
} list;
list *head;
void display(list*);
list* append(list*);
void reverse(list*);
int main()
{
int p,k,m;
list *d;
d=(list*)malloc(sizeof(list));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
reverse(head);
ARKADEEP DEY (CSE2015/030) CS392
17
scanf("%d",&p);
return 0;
}
list* append(list *l){
char c;
list *node;
node=(list*)malloc(sizeof(list));
printf("Enter the data :");
scanf("%d",&node->data);
node->link=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->link=node;
l=node ;
}
return(l);
}
void display(list *h){
while(h!=NULL){
printf("%d -> ",h->data);
h=h->link;
}
ARKADEEP DEY (CSE2015/030) CS392
18
printf("NULL\n");
printf("----------------------------------------------\n");
}
void reverse(list *h){
list *p,*q,*r;
p=h;
q=NULL;
while(p!=NULL){
r=q;
q=p;
p=p->link;
q->link=r;
}
h=q;
printf("The reversed list is:\n");
while(h!=NULL){
printf("%d ->",h->data);
h=h->link;
}
printf("NULL");
}
ARKADEEP DEY (CSE2015/030) CS392
19
Q-11>singly link list insertion at beginning, end, after a node, before node:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
typedef struct list{
int data;
list *link;
} list;
list *head;
void display(list*);
list* append(list*);
void insert_beg(list*);
void insert_end(list*);
void insert_aft(list*,int);
void insert_bef(list*,int);
int main()
{
int p,k,m;
list *d;
d=(list*)malloc(sizeof(list));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y')
ARKADEEP DEY (CSE2015/030) CS392
20
{
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
printf("------- MENU --------\n ");
printf("1 = Insert at begining \n");
printf("2 = Insert at end \n");
printf("3 = Insert before node \n");
printf("4 = Insert after node \n");
printf("Enter your choice :");
scanf("%d",&m);
switch(m)
{
case 1:insert_beg(head);
display(head);
break;
case 2:insert_end(head);
display(head);
break;
case 3:printf("Enter the node position :");
scanf("%d",&p);
insert_bef(head,p);
ARKADEEP DEY (CSE2015/030) CS392
21
display(head);
break;
case 4:printf("Enter the node position :");
scanf("%d",&p);
insert_aft(head,p);
display(head);
break;
default : printf("Wrong choice");
}
scanf("%d",&p);
return 0;
}
list* append(list *l)
{
char c;
list *node;
node=(list*)malloc(sizeof(list));
printf("Enter the data :");
scanf("%d",&node->data);
node->link=NULL;
if(head==NULL){
head=node;
l=head;
}
else
ARKADEEP DEY (CSE2015/030) CS392
22
{
l->link=node;
l=node ;
}
return(l);
}
void display(list *h)
{
while(h!=NULL)
{
printf("%d -> ",h->data);
h=h->link;
}
printf("NULL\n");
printf("----------------------------------------------\n");
}
void insert_bef(list* h,int pos)
{
int c=1;
list *x;
x=(list*)malloc(sizeof(list));
printf("Enter data of new node : ");
scanf("%d",&x->data);
x->link=NULL;
while(h!=NULL)
ARKADEEP DEY (CSE2015/030) CS392
23
{
c++;
if(c==pos)
{
x->link=h->link;
h->link=x;
break;
}
else
{
h=h->link;
}
}
}
void insert_aft(list* h,int pos)
{
int c=0;
list *x;
x=(list*)malloc(sizeof(list));
printf("Enter data of new node : ");
scanf("%d",&x->data);
x->link=NULL;
while(h!=NULL)
{
c++;
ARKADEEP DEY (CSE2015/030) CS392
24
if(c==pos)
{
x->link=h->link;
h->link=x;
break;
}
else{
h=h->link;
}
}
}
void insert_beg(list* h)
{
list *x;
x=(list*)malloc(sizeof(list));
printf("Enter data of new node : ");
scanf("%d",&x->data);
x->link=h;
head=x;
}
void insert_end(list* h){
list *x;
x=(list*)malloc(sizeof(list));
printf("Enter data of new node : ");
scanf("%d",&x->data);
ARKADEEP DEY (CSE2015/030) CS392
25
x->link=NULL;
while(h->link!=NULL)
h=h->link;
h->link=x;
}
Q-12>singly link list deletion from head node, last node, middle node:
#include <stdio.h> #include <conio.h> #include <malloc.h>
typedef struct list{
int data; list *link; } list;
list *head; void display(list*); list* append(list*); void del_beg(list*); void del_end(list*); void del_mid(list*,int);
int main()
{
int p,k,m; list *d; d=(list*)malloc(sizeof(list));
ARKADEEP DEY (CSE2015/030) CS392
26
head=NULL; d=head; char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
scanf("%c",&c);
}
display(head);
printf("------- MENU --------\n ");
printf("1 = Delete from begining \n");
printf("2 = Delete from end \n");
printf("3 = Delete from middle \n");
printf("Enter your choice :");
scanf("%d",&m);
switch(m){
case 1:del_beg(head)
display(head);
break;
case 2:del_end(head);
display(head);
break;
case 3:printf("Enter the node to delete :");
scanf("%d",&p);
del_mid(head,p);
ARKADEEP DEY (CSE2015/030) CS392
27
display(head);
break;
default : printf("Wrong choice");
}
scanf("%d",&p);
return 0;
}
list* append(list *l){
char c;
list *node;
node=(list*)malloc(sizeof(list));
printf("Enter the data :");
scanf("%d",&node->data);
node->link=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->link=node;
l=node ;
}
return(l);
}
void display(list *h){
ARKADEEP DEY (CSE2015/030) CS392
28
while(h!=NULL){
printf("%d -> ",h->data);
h=h->link;
}
printf("NULL\n");
printf("----------------------------------------------\n");
}
void del_beg(list *h){
list *x;
x=h;
head=h->link;
printf("Pop = %d\n",x->data);
free(x);
}
void del_end(list *h){
list *x;
while(h->link->link!=NULL){
h=h->link;
}
x=h->link;
h->link=NULL;
printf("Pop = %d\n",x->data);
free(x);
}
void del_mid(list *h,int p){
ARKADEEP DEY (CSE2015/030) CS392
29
list *x;
int c=0;
while(h->link->link!=NULL){
c++;
if(c!=(p-1))
h=h->link;
else{
x=h->link;
break;
}
}
h->link=x->link;
printf("Pop = %d\n",x->data);
free(x);
}
Double linkeD list
Q-13>create display and count double link list:
ARKADEEP DEY (CSE2015/030) CS392
30
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
typedef struct dnode{
int data;
dnode *rlink;
dnode *llink;
} dnode;
dnode *append(dnode*);
void count(dnode *);
void display(dnode*);
dnode *head;
int main()
{
char c='y';
int i;
dnode *d;
head=NULL;
d=head;
while(c=='Y' || c=='y'){
d=append(d);
printf("Add another node (y/n)?");
fflush(stdin);
scanf("%c",&c);
ARKADEEP DEY (CSE2015/030) CS392
31
}
display(head);
count(head);
scanf("%d",&i);
return 0;
}
dnode* append(dnode *h){
dnode *x;
x=(dnode*)malloc(sizeof(dnode));
printf("Enter the data :");
scanf("%d",&x->data);
x->rlink=NULL;
if(h==NULL){
head=x;
h=head;
}
else{
x->llink=h;
h->rlink=x;
h=x;
}
return h;
}
void display(dnode* h){
while(h!=NULL){
ARKADEEP DEY (CSE2015/030) CS392
32
printf("%d ->",h->data);
h=h->rlink;
}
printf("NULL");
}
void count(dnode *h){
int c=0;
while(h!=NULL){
c++;
h=h->rlink;
}
printf("\n NO.of nodes = %d \n",c);
}
void del(dnode* h){
dnode *x;
int d;
printf("Enter the value to delete :");
scanf("%d",&d);
while(h!=NULL){
if(h->data==d){
x=h;
h->llink->rlink=h->rlink;
h->rlink->llink=h->llink;
break;
}
ARKADEEP DEY (CSE2015/030) CS392
33
else{
h=h->rlink;
}
}
free(x);
}
Q-14>doubly link list insertion at beginning at after a node and before a node:
#include <stdio.h>
#include <conio.h>
#include <Malloc.h>
typedef struct dnode{
int data;
dnode *llink;
dnode *rlink;
} dnode;
dnode *head;
void display(dnode*);
dnode* append(dnode*);
void insert_beg(dnode*);
ARKADEEP DEY (CSE2015/030) CS392
34
void insert_end(dnode*);
void insert_aft(dnode*,int);
void insert_bef(dnode*,int);
int main()
{
int p,k,m;
dnode *d;
d=(dnode*)malloc(sizeof(dnode));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
printf("------- MENU --------\n ");
printf("1 = Insert at begining \n");
printf("2 = Insert at end \n");
printf("3 = Insert before node \n");
printf("4 = Insert after node \n");
printf("Enter your choice :");
scanf("%d",&m);
ARKADEEP DEY (CSE2015/030) CS392
35
switch(m){
case 1:insert_beg(head);
display(head);
break;
case 2:insert_end(head);
display(head);
break;
case 3:printf("Enter the node position :");
scanf("%d",&p);
insert_bef(head,p);
display(head);
break;
case 4:printf("Enter the node position :");
scanf("%d",&p);
insert_aft(head,p);
display(head);
break;
default : printf("Wrong choice");
}
scanf("%d",&p);
return 0;
}
dnode* append(dnode *l){
char c;
dnode *node;
ARKADEEP DEY (CSE2015/030) CS392
36
node=(dnode*)malloc(sizeof(dnode));
printf("Enter the data :");
scanf("%d",&node->data);
node->rlink=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->rlink=node;
node->llink=l;
l=node ;
}
return(l);
}
void display(dnode *h){
while(h!=NULL){
printf("%d -> ",h->data);
h=h->rlink;
}
printf("NULL\n");
printf("----------------------------------------------\n");
}
void insert_bef(dnode* h,int pos){
int c=1;
ARKADEEP DEY (CSE2015/030) CS392
37
dnode *x;
x=(dnode*)malloc(sizeof(dnode));
printf("Enter data of new node : ");
scanf("%d",&x->data);
x->rlink=NULL;
while(h!=NULL){
c++;
if(c==pos){
x->rlink=h->rlink;
h->rlink->llink=x;
x->llink=h;
h->rlink=x;
break;
}
else{
h=h->rlink;
}
}
}
void insert_aft(dnode* h,int pos){
int c=0;
dnode *x;
x=(dnode*)malloc(sizeof(dnode));
printf("Enter data of new node : ");
scanf("%d",&x->data);
ARKADEEP DEY (CSE2015/030) CS392
38
x->rlink=NULL;
while(h!=NULL){
c++;
if(c==pos){
x->rlink=h->rlink;
h->rlink->llink=x;
x->llink=h;
h->rlink=x;
break;
}
else{
h=h->rlink;
}
}
}
void insert_beg(dnode* h){
dnode *x;
x=(dnode*)malloc(sizeof(dnode));
printf("Enter data of new node : ");
scanf("%d",&x->data);
x->rlink=h;
h->llink=x;
head=x;
}
void insert_end(dnode* h){
ARKADEEP DEY (CSE2015/030) CS392
39
dnode *x;
x=(dnode*)malloc(sizeof(dnode));
printf("Enter data of new node : ");
scanf("%d",&x->data);
x->rlink=NULL;
while(h->rlink!=NULL)
h=h->rlink;
h->rlink=x;
x->llink=h;
}
Q-15>deletion of head node, middle node, last node of a doubly link list:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
typedef struct dnode{
int data;
ARKADEEP DEY (CSE2015/030) CS392
40
dnode *rlink;
dnode *llink;
} dnode;
dnode *head;
void display(dnode*);
dnode* append(dnode*);
void del_beg(dnode*);
void del_end(dnode*);
void del_mid(dnode*,int);
int main()
{
int p,k,m;
dnode *d;
d=(dnode*)malloc(sizeof(dnode));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
printf("------- MENU --------\n ");
ARKADEEP DEY (CSE2015/030) CS392
41
printf("1 = Delete from begining \n");
printf("2 = Delete from end \n");
printf("3 = Delete from middle \n");
printf("Enter your choice :");
scanf("%d",&m);
switch(m){
case 1:del_beg(head);
display(head);
break;
case 2:del_end(head);
display(head);
break;
case 3:printf("Enter the node to delete :");
scanf("%d",&p);
del_mid(head,p);
display(head);
break;
default : printf("Wrong choice");
}
scanf("%d",&p);
return 0;
}
dnode* append(dnode *l){
char c;
dnode *node;
ARKADEEP DEY (CSE2015/030) CS392
42
node=(dnode*)malloc(sizeof(dnode));
printf("Enter the data :");
scanf("%d",&node->data);
node->rlink=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->rlink=node;
node->llink=l;
l=node ;
}
return(l);
}
void display(dnode *h){
while(h!=NULL){
printf("%d -> ",h->data);
h=h->rlink;
}
printf("NULL\n");
printf("----------------------------------------------\n");
}
void del_beg(dnode *h){
dnode *x;
ARKADEEP DEY (CSE2015/030) CS392
43
x=h;
head=h->rlink;
printf("Pop = %d\n",x->data);
free(x);
}
void del_end(dnode *h){
dnode *x;
while(h->rlink->rlink!=NULL){
h=h->rlink;
}
x=h->rlink;
h->rlink=NULL;
printf("Pop = %d\n",x->data);
free(x);
}
void del_mid(dnode *h,int p){
dnode *x;
int c=0;
while(h->rlink->rlink!=NULL){
c++;
if(c!=(p-1))
h=h->rlink;
else{
x=h->rlink;
break;
ARKADEEP DEY (CSE2015/030) CS392
44
}
}
h->rlink=x->rlink;
x->rlink->llink=h;
printf("Pop = %d\n",x->data);
free(x);
}
circulAr AnD Double circulAr linkeD list
Q-16>a>creation, insertion , deletion, count, display of a circular link list:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>typedef struct list{
int data;
list *link;
} list;
list *head;
void display(list*);
list* append(list*);
ARKADEEP DEY (CSE2015/030) CS392
45
int count(list*);
void insert(list*);
void del(list*);
int main()
{
int p,k;
list *d;
d=(list*)malloc(sizeof(list));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
printf("\nThe no.of nodes = %d\n",count(head));
del(head);
display(head);
insert(head);
display(head);
scanf("%d",&p);
return 0;
ARKADEEP DEY (CSE2015/030) CS392
46
}
list* append(list *l){
char c;
list *node;
node=(list*)malloc(sizeof(list));
printf("\nEnter the data :");
scanf("%d",&node->data);
node->link=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->link=node;
node->link=head;
l=node ;
}
return(l);
}
void display(list *h){
do{
printf("[%d|%u] -> ",h->data,h);
h=h->link;
}while(h!=head);
printf("[%d|%u] -> ",h->data,h);
ARKADEEP DEY (CSE2015/030) CS392
47
printf("\n----------------------------------------------\n");
}
int count(list *h){
int c=0;
do{
c++;
h=h->link;
}while(h!=head);
return c;
}
void del(list *h){
list *x;
x=h;
head=h->link;
h=head;
printf("Pop = %d\n",x->data);
while(h->link!=x)
h=h->link;
h->link=head;
free(x);
}
void insert(list* h){
list *x;
x=(list*)malloc(sizeof(list));
printf("Enter data of new node : ");
ARKADEEP DEY (CSE2015/030) CS392
48
scanf("%d",&x->data);
x->link=h;
while(h->link!=head)
h=h->link;
h->link=x;
head=x;
}
Q-17> & Q-18> creation, count, display of a doubly circular link list:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
typedef struct dnode{
int data;
dnode *rlink;
dnode *llink;
} dnode;
ARKADEEP DEY (CSE2015/030) CS392
49
dnode *head;
void display(dnode*);
dnode* append(dnode*);
int count(dnode*);
int main()
{
int p,k;
dnode *d;
d=(dnode*)malloc(sizeof(dnode));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
printf("\nThe no.of nodes = %d\n",count(head));
scanf("%d",&p);
return 0;
}
dnode* append(dnode *l){
char c;
ARKADEEP DEY (CSE2015/030) CS392
50
dnode *node;
node=(dnode*)malloc(sizeof(dnode));
printf("\nEnter the data :");
scanf("%d",&node->data);
node->rlink=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->rlink=node;
node->llink=l;
node->rlink=head;
head->llink=node;
l=node ;
}
return(l);
}
void display(dnode *h){
do{
printf("[%u|%d|%u] -> ",h->llink,h->data,h->rlink);
h=h->rlink;
}while(h!=head);
printf("[%u|%d|%u] -> ",h->llink,h->data,h->rlink);
printf("\n----------------------------------------------\n");
ARKADEEP DEY (CSE2015/030) CS392
51
}
int count(dnode *h){
int c=0;
do{
c++;
h=h->rlink;
}while(h!=head);
return c;
}
PolynomiAl rePresentAtion using linkeD list
Q-19>polynomial representation of linked list:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct link
{
ARKADEEP DEY (CSE2015/030) CS392
52
int coef;
int deg;
struct link *next;
};
typedef struct link node;
node* create(node*);
void display(node*);
int main()
{
char ch;
int num,cho;
node *head,*tmp;
head=NULL;
do
{
printf("\n=========MAIN MENU=========");
printf("\nPolynomial Creation....1");
printf("\nAdd and Display........2");
printf("\nEXIT...................0");
printf("\n===========================");
printf("\nENTER CHOICE : ");
fflush(stdin);
scanf("%d",&cho);
ARKADEEP DEY (CSE2015/030) CS392
53
switch(cho)
{
case 1:
head=create(head);
break;
case 2:
display(head);
break;
case 0:
exit(0);
default:
printf("\nWRONG CHOICE!!\n");
}
getch();
}while(1);
return 0;
}
node* create(node* head)
{
node *tmp;
int num;
char ch;
if(head==NULL)
{
ARKADEEP DEY (CSE2015/030) CS392
54
head=(node *)malloc(sizeof(node));
tmp=head;
do
{
printf("\nEnter co-efficient :");
scanf("%d",&num);
head->coef=num;
printf("\nEnter degree :");
scanf("%d",&num);
head->deg=num;
printf("\nAdd more [Y/N]:");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y' || ch=='Y')
{
head->next=(node*)malloc(sizeof(node));
head=head->next;
continue;
}
else
{
head->next=NULL;
break;
ARKADEEP DEY (CSE2015/030) CS392
55
}
}while(1);
//head=tmp;
return head;
}
else
{
printf("\nLink list already created");
return head;
}
}
void display(node *head)
{
node *p;
p=head;
while(p!=NULL)
{
printf("[%d|%d|%u]->",p->coef,p->deg,p->next);
p=p->next;
}
}
ARKADEEP DEY (CSE2015/030) CS392
56
Q-20>creation and addition of two polynomial link list:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct link
{
int coef;
int deg;
struct link *next;
};
typedef struct link node;
node* create(node*);
void list(node*,node*);
int main()
{
char ch;
int num,cho;
node *head1,*head2,*tmp;
head1=head2=NULL;
do
{
ARKADEEP DEY (CSE2015/030) CS392
57
printf("\n=========MAIN MENU=========");
printf("\nPolynomial Creation [1]....1");
printf("\nPolynomial Creation [2]....2");
printf("\nAdd and Display............3");
printf("\nEXIT.......................0");
printf("\n===========================");
printf("\nENTER CHOICE : ");
fflush(stdin);
scanf("%d",&cho);
switch(cho)
{
case 1:
head1=create(head1);
break;
case 2:
head2=create(head2);
break;
case 3:
list(head1,head2);
break;
case 0:
exit(0);
ARKADEEP DEY (CSE2015/030) CS392
58
default:
printf("\nWRONG CHOICE!!\n");
}
getch();
}while(1);
return 0;
}
node* create(node* head)
{
node *tmp;
int num;
char ch;
if(head==NULL)
{
head=(node *)malloc(sizeof(node));
tmp=head;
do
{
printf("\nEnter co-efficient :");
scanf("%d",&num);
head->coef=num;
printf("\nEnter degree :");
scanf("%d",&num);
head->deg=num;
printf("\nAdd more [Y/N]:");
ARKADEEP DEY (CSE2015/030) CS392
59
fflush(stdin);
scanf("%c",&ch);
if(ch=='y' || ch=='Y')
{
head->next=(node*)malloc(sizeof(node));
head=head->next;
continue;
}
else
{
head->next=NULL;
break;
}
}while(1);
head=tmp;
return head;
}
else
{
printf("\nLink list already created");
return head;
}
}
void list(node *head1,node *head2)
{
ARKADEEP DEY (CSE2015/030) CS392
60
node *tmp1,*tmp2;
int maxDeg=0,coef;
if(head1==NULL || head2==NULL)
{
printf("\nLink List not created");
}
tmp1=head1;
tmp2=head2;
while(tmp1!=NULL)
{
if(maxDeg<tmp1->deg)
maxDeg=tmp1->deg;
tmp1=tmp1->next;
}
while(tmp2!=NULL)
{
if(maxDeg<tmp2->deg)
maxDeg=tmp2->deg;
tmp2=tmp2->next;
}
do
{
tmp1=head1;
tmp2=head2;
coef=0;
ARKADEEP DEY (CSE2015/030) CS392
61
while(tmp1!=NULL)
{
if(tmp1->deg==maxDeg)
{
coef+=tmp1->coef;
//deg+=tmp1->deg;
break;
}
tmp1=tmp1->next;
}
while(tmp2!=NULL)
{
if(tmp2->deg==maxDeg)
{
coef+=tmp2->coef;
//deg+=tmp2->deg;
break;
}
tmp2=tmp2->next;
}
if(coef!=0)
printf("%dx^%d + ",coef,maxDeg);
maxDeg--;
if(maxDeg==-1)
return;
ARKADEEP DEY (CSE2015/030) CS392
62
}while(1);
}
Q-21>Program to multiply two polynomial using linked list.
#include<stdio.h>
#include<stdlib.h>
ARKADEEP DEY (CSE2015/030) CS392
63
struct node {
float coef;
int expo;
struct node *link;
};
struct node *create(struct node *); struct node *insert_s(struct node *,float,int); struct node *insert(struct node *,float,int); void display(struct node *ptr); void poly_add(struct node *,struct node *); void poly_mult(struct node *,struct node *); main( )
{ struct node *start1=NULL,*start2=NULL; printf("Enter polynomial 1 :\n"); start1=create(start1); printf("Enter polynomial 2 :\n"); start2=create(start2); printf("Polynomial 1 is : "); display(start1); printf("Polynomial 2 is : "); display(start2); poly_add(start1, start2); poly_mult(start1, start2); } /*End of main()*/
struct node *create(struct node *start) { int i,n,ex; float co; printf("Enter the number of terms : "); scanf("%d",&n); for(i=1;i<=n;i++){
ARKADEEP DEY (CSE2015/030) CS392
64
printf("Enter coeficient for term %d : ",i); scanf("%f",&co); printf("Enter exponent for term %d : ",i); scanf("%d",&ex); start=insert_s(start,co,ex); } return start; } /*End of create()*/ struct node *insert_s(struct node *start,float co,int ex) {
struct node *ptr,*tmp; tmp=(struct node *)malloc(sizeof(struct node)); tmp->coef=co; tmp->expo=ex; /*list empty or exp greater than first one */ if(start==NULL || ex > start->expo) { tmp->link=start; start=tmp; } else { ptr=start; while(ptr->link!=NULL && ptr->link->expo >= ex) ptr=ptr->link; tmp->link=ptr->link; ptr->link=tmp; } return start; } /*End of insert()*/ struct node *insert(struct node *start,float co,int ex) { struct node *ptr,*tmp; tmp=(struct node *)malloc(sizeof(struct node)); tmp->coef=co; tmp->expo=ex; /*If list is empty*/ if(start==NULL) { tmp->link=start; start=tmp;
ARKADEEP DEY (CSE2015/030) CS392
65
} else /*Insert at the end of the list*/ { ptr=start; while(ptr->link!=NULL) ptr=ptr->link; tmp->link=ptr->link; ptr->link=tmp; } return start; } /*End of insert()*/
void display(struct node *ptr) { if(ptr==NULL) { printf("Zero polynomial\n"); return; } while(ptr!=NULL) { printf("(%.1fx^%d)", ptr->coef,ptr->expo); ptr=ptr->link; if(ptr!=NULL)
printf(" + ");
else printf("\n"); } }/*End of display()*/
void poly_add(struct node *p1,struct node *p2) { struct node *start3; start3=NULL; while(p1!=NULL && p2!=NULL) { if(p1->expo > p2->expo) { start3=insert(start3,p1->coef,p1->expo); p1=p1->link;
ARKADEEP DEY (CSE2015/030) CS392
66
} else if(p2->expo > p1->expo) { start3=insert(start3,p2->coef,p2->expo); p2=p2->link; } else if(p1->expo==p2->expo) { start3=insert(start3,p1->coef+p2->coef,p1->expo); p1=p1->link; p2=p2->link; }
} /*if poly2 has finished and elements left in poly1*/ while(p1!=NULL) { start3=insert(start3,p1->coef,p1->expo); p1=p1->link; } /*if poly1 has finished and elements left in poly2*/ while(p2!=NULL) { start3=insert(start3,p2->coef,p2->expo); p2=p2->link; } printf("Added polynomial is : "); display(start3); } /*End of poly_add() */
void poly_mult(struct node *p1, struct node *p2) { struct node *start3; struct node *p2_beg = p2; start3=NULL; if(p1==NULL || p2==NULL) { printf("Multiplied polynomial is zero polynomial\n"); return; }
ARKADEEP DEY (CSE2015/030) CS392
67
while(p1!=NULL) { p2=p2_beg; while(p2!=NULL) { start3=insert_s(start3,p1->coef*p2->coef,p1->expo+p2->expo); p2=p2->link; } p1=p1->link; } printf("Multiplied polynomial is : "); display(start3); } /*End of poly_mult()*/
stAck-imPlementAtion AnD exPression evAluAtion
Q-22>Implement stack using array:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
ARKADEEP DEY (CSE2015/030) CS392
68
#define max 10
int tos=-1;
void push();
int pop();
void display();
int stack[max];
int main()
{
int n,p,val;
do
{
printf("\n[Press 1 for push]");
printf("\n[Press 2 for pop]");
printf("\n[Press 3 for display]");
printf("\n[Press 4 for exit]");
printf("\n\nenter your choice:");
scanf("%d",&n);
switch(n)
{
case 1:
if(tos<max)
push();
else
printf("\nStack overflow...!!!");
break;
ARKADEEP DEY (CSE2015/030) CS392
69
case 2:
if(tos>-1)
{
p=pop();
printf("\n Value popped = %d...!!!",p);
}
else
printf("\n Stack underflow...!!!");
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\n Wrong ENTRY...!!!");
break;
}
printf("\n enter 1 for continue:");
scanf("%d",&val);
}while(val==1);
getch();
return 0;
}
ARKADEEP DEY (CSE2015/030) CS392
70
void push()
{
int n;
printf("\nEnter data:");
scanf("%d",&n);
stack[++tos]=n;
}
int pop()
{
return (stack[tos--]);
}
void display()
{
int i;
printf("\n TOS--->");
for(i=tos;i>=0;i--)
printf("[%d]",stack[i]);
}
ARKADEEP DEY (CSE2015/030) CS392
71
Q-23>Implement stack using link list:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
int tos=-1;
typedef struct node
{
int data;
struct node *link;
}node;
node *head;
void push(node *);
int pop(node *);
void display(node *);
int main()
{
node *list;
head=NULL;
list=head;
int n,val,p;
ARKADEEP DEY (CSE2015/030) CS392
72
do
{
printf("\n[Press 1 for push]");
printf("\n[Press 2 for pop]");
printf("\n[Press 3 for display]");
printf("\n[Press 4 for exit]");
printf("\n\nenter your choice:");
scanf("%d",&n);
switch(n)
{
case 1:
push(head);
tos++;
break;
case 2:
if(tos==-1)
{
printf("\n Stack underflow...!!!");
}
else
{
p=pop(head);
printf("\n Value popped = %d...!!!",p);
tos--;
ARKADEEP DEY (CSE2015/030) CS392
73
}
break;
case 3:
display(head);
break;
case 4:
exit(0);
break;
default:
printf("\n Wrong ENTRY...!!!");
break;
}
printf("\n enter 1 for continue:");
scanf("%d",&val);
}while(val==1);
getch();
return 0;
}
int pop(node *l)
{
node *temp;
int val;
if(l->link==NULL)
{
temp=head;
ARKADEEP DEY (CSE2015/030) CS392
74
val=temp->data;
free(temp);
head=NULL;
return (val);
}
else
{
while(l!=NULL)
{
if(l->link->link==NULL)
{
temp=l->link;
l->link=NULL;
val=temp->data;
free(temp);
return (val);
}
else
l=l->link;
}
}
}
void display(node *l)
{
while(l!=NULL)
ARKADEEP DEY (CSE2015/030) CS392
75
{ printf("\n ");
printf("[%d ] ",l->data);
l=l->link;
}
printf(" <--------TOS ");
}
void push(node *l)
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->link=NULL;
if(l==NULL)
{
printf("\n Enter insert node data:");
scanf("%d",&temp->data);
head=temp;
return ;
}
else
{
while(l!=NULL)
{
if(l->link==NULL)
{
break;
ARKADEEP DEY (CSE2015/030) CS392
76
}
else
l=l->link;
}
printf("\n Enter insert node data:");
scanf("%d",&temp->data);
temp->link=NULL;
l->link=temp;
}
}
ARKADEEP DEY (CSE2015/030) CS392
77
Q-24>Convert an infix exp. to postfix exp:
#include<stdio.h>
#include<string.h>
#define size 10
char stack[size];
int tos=0,ele;
void push(int);
char pop();
void show();
int isempty();
int isfull();
char infix[30],output[30];
int prec(char);
int main()
{
int i=0,j=0,k=0,length;
char temp;
printf("\nEnter an infix expression:");
scanf("%s",infix);
printf("\nThe infix expresson is %s",infix);
length=strlen(infix);
for(i=0;i<length;i++)
ARKADEEP DEY (CSE2015/030) CS392
78
{
//Numbers are added to the out put QUE
if(infix[i]!='+' && infix[i]!='-' && infix[i]!='*' && infix[i]!='/' && infix[i]!='^' && infix[i]!=')' && infix[i]!='(' )
{
output[j++]=infix[i];
printf("\nThe element added to Q is:%c",infix[i]);
}
//If an operator or a bracket is encountered...
else
{
if(tos==0) //If there are no elements in the stack, the operator is added to it
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
}
else
{ //Operators or pushed or poped based on the order of precedence
if(infix[i]!=')' && infix[i]!='(')
{
if( prec(infix[i]) <= prec(stack[tos-1]) )
{
temp=pop();
printf("\n the poped element is :%c",temp);
ARKADEEP DEY (CSE2015/030) CS392
79
output[j++]=temp;
push(infix[i]);
printf("\n The pushed element is :%c",infix[i]);
show();
}
else
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
show();
}
}
else
{
if(infix[i]=='(')
{
push(infix[i]);
printf("\nThe pushed-- element is:%c",infix[i]);
}
if(infix[i]==')')
{
temp=pop();
while(temp!='(')
{output[j++]=temp;
printf("\nThe element added to Q is:%c",temp);
ARKADEEP DEY (CSE2015/030) CS392
80
//temp=pop();
printf("\n the poped element is :%c",temp);
temp=pop();}
}
}
}
}
printf("\nthe infix expression is: %s",output);
}
while(tos!=0)
{
output[j++]=pop();
}
printf("the infix expression is: %s\n",output);
getch();
}
//Functions for operations on stack
void push(int ele)
{
stack[tos]=ele;
tos++;
}
char pop()
ARKADEEP DEY (CSE2015/030) CS392
81
{
tos--;
return(stack[tos]);
}
void show()
{
int x=tos;
printf("--The Stack elements are.....");
while(x!=0)
printf("%c, ",stack[--x]);
}
int prec(char symbol)
{
if(symbol== '(')
return 0;
if(symbol== ')')
return 0;
if(symbol=='+' || symbol=='-')
return 1;
if(symbol=='*' || symbol=='/')
return 2;
if(symbol=='^')
return 3;
return 0;
}
ARKADEEP DEY (CSE2015/030) CS392
82
.
Q-25>Convert an infix exp. to prefix exp:
#include<stdio.h> #include<conio.h> #include<string.h> #define MAX 20 char stack[MAX]; int top = -1; char pop(); void push(char item); int prcd(char symbol) {
ARKADEEP DEY (CSE2015/030) CS392
83
switch(symbol) { case '+': case '-': return 2; case '*': case '/': return 4; case '^': case '$': return 6; case '(': case ')': case '#': return 1; }
}
int isoperator(char symbol) { switch(symbol) { case '+': case '-': case '*': case '/': case '^': case '$': case '(': case ')': return 1; default: return 0;
}
}
void convertip(char infix[],char prefix[]) {
ARKADEEP DEY (CSE2015/030) CS392
84
int i,symbol,j=0;
char test[MAX];
infix=strrev(infix);
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
{
prefix[j]=symbol;
j++;
}else {
if(symbol==')')
{
push(symbol);
}else if(symbol=='(')
{
while(stack[top]!=')')
{
prefix[j]=pop();
j++;
}
pop();//pop ou
}
else
ARKADEEP DEY (CSE2015/030) CS392
85
{
if(prcd(symbol)>prcd(stack[top]))
{
push(symbol);
}else
{
while(prcd(symbol)<=prcd(stack[top]))
{
prefix[j]=pop();
j++;
}
push(symbol);
}//end of else.
}//end of else.
}//end of else.
}//end of for.
while(stack[top]!='#')
{
prefix[j]=pop();
j++;
}
prefix[j]='\0';//null terminate string.
prefix=strrev(prefix);
}
int main()
ARKADEEP DEY (CSE2015/030) CS392
86
{
char infix[20],prefix[20];
printf("Enter the valid infix string:\n");
gets(infix);
convertip(infix,prefix);
printf("The corresponding prefix string is:\n");
puts(prefix);
getch();
return 0;
}
void push(char item)
{
top++;
stack[top]=item;
}
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
ARKADEEP DEY (CSE2015/030) CS392
87
Queue
Q-26>Implement queue using array:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#define max 10
int fr=0;
int rr=0;
int q[max];
void push();
int pop();
void display();
int main()
{
int n,p,val;
ARKADEEP DEY (CSE2015/030) CS392
88
do
{
printf("\n[Press 1 for push]");
printf("\n[Press 2 for pop]");
printf("\n[Press 3 for display]");
printf("\n[Press 4 for exit]");
printf("\nenter your choice:");
scanf("%d",&n);
switch(n)
{
case 1:
if(rr<max)
push();
else
printf("\nQueue overflow...!!!");
break;
case 2:
if(fr!=rr && fr<max)
{
p=pop();
printf("\n Value popped = %d...!!! ",p);
}
else
printf("\n Queue underflow...!!!");
break;
ARKADEEP DEY (CSE2015/030) CS392
89
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\n Wrong ENTRY...!!!");
break;
}
printf("\n enter 1 for continue:");
scanf("%d",&val);
}while(val==1);
getch();
return 0;
}
void push()
{
int n;
printf("\nEnter data:");
scanf("%d",&n);
q[rr++]=n;
}
int pop()
{
ARKADEEP DEY (CSE2015/030) CS392
90
return (q[fr++]);
}
void display()
{
int i;
printf("\nFRONT->");
for(i=fr;i<rr;i++)
printf("[%d]",q[i]);
printf("<-REAR");
}
ARKADEEP DEY (CSE2015/030) CS392
91
Q-27> Implement queue using link list.
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
int fr=0;
int rr=0;
typedef struct node
{
int data;
struct node *link;
}node;
node *head;
node * push(node *);
int pop(node *);
void display(node *)
int main()
{
node *d;
head=NULL;
d=head;
int n,val,p;
do
{
ARKADEEP DEY (CSE2015/030) CS392
92
printf("\n[Press 1 for push]");
printf("\n[Press 2 for pop]");
printf("\n[Press 3 for display]");
printf("\n[Press 4 for exit]");
printf("\n\nenter your choice:");
scanf("%d",&n);
switch(n)
{
case 1:
d=push(d);
break;
case 2:
if(fr<rr)
{
p=pop(head);
printf("\n Value popped = %d...!!!",p);
}
else
printf("\n Stack underflow...!!!");
break;
case 3:
display(head);
break;
case 4:
exit(0);
ARKADEEP DEY (CSE2015/030) CS392
93
break;
default:
printf("\n Wrong ENTRY...!!!");
break;
}
printf("\n enter 1 for continue...!!!");
scanf("%d",&val);
}while(val==1);
getch();
return 0;
}
node * push(node *list)
{
node *temp;
temp=(node *)malloc(sizeof(node));
printf("\n Enter data:");
scanf("%d",&temp->data);
temp->link=NULL;
if(head==NULL)
{
head=temp;
list=head;
}
else
ARKADEEP DEY (CSE2015/030) CS392
94
{
list->link=temp;
list=temp;
}
rr++;
return (list);
}
int pop(node *l)
{
node *temp;
int val;
temp=head;
head=head->link;
val=temp->data;
free(temp);
fr++;
return (val);
}
void display(node *l)
{
printf("\nFRONT-> ");
while(l!=NULL)
{
printf("[ %d ] ",l->data);
l=l->link;
ARKADEEP DEY (CSE2015/030) CS392
95
}
printf(" <-REAR ");
}
Q-28> Implement D queue:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#define max 10
int fr=0;
int rr=0;
ARKADEEP DEY (CSE2015/030) CS392
96
int q[max];
void add_end();
int del_beg();
void add_beg();
int del_end();
void display()
int main()
{
int n,p,val;
do
{
printf("\n[Press 1 for add at end]");
printf("\n[Press 2 for delete at beginning]");
printf("\n[Press 3 for add at beginning]");
printf("\n[Press 4 for delete at end]");
printf("\n[Press 5 for display]");
printf("\n[Press 6 for exit]");
printf("\n\nenter your choice:");
scanf("%d",&n);
switch(n)
{
case 1:
if(rr<max)
add_end();
else
ARKADEEP DEY (CSE2015/030) CS392
97
printf("\nDequeue is full...!!!");
break;
case 2:
if(fr!=rr && fr<max)
{
p=del_beg();
printf("\n Value popped from beginning = %d...!!!",p);
}
else
printf("\n Dequeue is empty...!!!");
break;
case 3:
if(fr!=0 && fr<max)
{
add_beg();
}
else
printf("\n Dequeue is full...!!!");
break;
case 4:
if(rr!=0 || rr<max)
{
p=del_end();
printf("\n Value popped from end = %d...!!!",p);
}
ARKADEEP DEY (CSE2015/030) CS392
98
else
printf("\nDequeue empty...!!!");
break;
case 5:
display();
break;
case 6:
exit(0);
break;
default:
printf("\n Wrong ENTRY...!!!");
break;
}
printf("\n enter 1 for continue: ");
scanf("%d",&val);
}while(val==1);
getch();
return 0;
}
void add_end()
{
int n;
printf("\nEnter data:");
scanf("%d",&n);
q[rr++]=n;
ARKADEEP DEY (CSE2015/030) CS392
99
}
int del_beg()
{
return (q[fr++]);
}
void add_beg()
{
int n;
printf("\nEnter data:");
scanf("%d",&n);
fr--;
q[fr]=n;
}
int del_end()
{
rr--;
return (q[rr]);
}
void display()
{
int i;
printf("\nFRONT->");
for(i=fr;i<rr;i++)
printf("[%d]",q[i]);
printf("<-REAR");
ARKADEEP DEY (CSE2015/030) CS392
100
}
Q-29>circular queue:
#include<stdio.h>
#include<conio.h>
typedef struct node
{
int data;
struct node *link;
}node;
ARKADEEP DEY (CSE2015/030) CS392
101
node *front;
node *rear;
node *insert_end(node*);
node* del_first(node*);
void display(node*);
int main()
{
char ch;
int c,e;
ch='y';
front=NULL;
rear=front;
do
{
printf("\n---------------------------------------");
printf("\n |enter 1 to insert in the queue.|");
printf("\n |enter 2 to delete from the queue.|");
printf("\n |enter 3 for display the linklist|");
printf("\n |enter 4 for exit.|");
printf("\n----------------------------------------");
printf("\n enter your choice:");
scanf("%d",&c);
switch(c)
{
case 1:
ARKADEEP DEY (CSE2015/030) CS392
102
ch='y';
while(ch=='y'||ch=='Y')
{
rear=insert_end(rear);
printf("\n do you want to continue:");
fflush(stdin);
ch=getch();
}
break;
case 2:
front=del_first(front);
printf("\n deleted from the queue is sucessfull.");
break;
case 3:
display(front);
break;
case 4:
exit(0);
default:
printf("\ninvalid choice");
}
}while(1);
}
node* insert_end(node *rear)
{
ARKADEEP DEY (CSE2015/030) CS392
103
node *x;
x=(node*)malloc(sizeof(node));
printf("\n enter data:");
scanf("%d",&x->data);
x->link=NULL;
if(front==NULL)
{
front=x;
rear=front;
}
else
{
rear->link=x;
rear=x;
rear->link=front;
}
return(rear);
}
void display(node *l)
{
if(l==NULL)
printf("\n the queue is empty.");
printf("\n[%u]->",l);
while(l->link!=front)
{
ARKADEEP DEY (CSE2015/030) CS392
104
printf("[%d|%u]->",l->data,l->link);
l=l->link;
}
printf("[%d|%u]",l->data,l->link);
}
node* del_first(node* front)
{
node* x;
node *l;
printf("\n %d is to be deleted from the queue.",front->data);
printf("\n.........................");
l=front;
while(l->link->link!=front)
{
l=l->link;
}
l->link->link=front->link;
x=front;
front=front->link;
free(x);
return front;
}
ARKADEEP DEY (CSE2015/030) CS392
105
seArching
Q-30>linear search using recursion:
#include <stdio.h>
#include <conio.h>
int srch(int,int ar[],int);
int main()
{
int pos,i,n,ar[20],num;
printf("Enter size of array : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ARKADEEP DEY (CSE2015/030) CS392
106
printf("ar[%d]=",i);
scanf("%d",&ar[i]);
}
printf("Which element you want to search : ");
scanf("%d",&num);
pos=srch(n,ar,num);
printf("Number found at position [%d]\n",pos+1);
getch();
return 0;
}
int srch(int n,int ar[],int num)
{
if(ar[n]==num)
return n;
else
return srch(n-1,ar,num);
ARKADEEP DEY (CSE2015/030) CS392
107
}
Q-31>linear searching using iteration:
#include<stdio.h>
#include<conio.h>
int l_search(int [],int,int);
int main()
{
int a[20],n,i,x,pos;
printf("\nenter the no. of elements:");
scanf("%d",&n);
printf("\nthe elements are:");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d",&a[i]);
}
ARKADEEP DEY (CSE2015/030) CS392
108
printf("\nenter the no. you want search:");
scanf("%d",&x);
pos=l_search(a,n,x);
if(pos==-1)
printf("\nelement not found.");
else
printf("\nelement %d found at position [%d].",x,(pos+1));
getch();
return 0;
}
int l_search(int a[],int n,int x)
{
int i=0;
a[n]=x;
while(a[i]!=x)
{
i++;
}
if(i==n)
return -1;
else
return i;
ARKADEEP DEY (CSE2015/030) CS392
109
}
Q-32>binary search using iteration:
#include <stdio.h>
#include <conio.h>
int srch(int,int ar[],int);
int main()
{
int i,n,ar[20],num,pos;
printf("Enter size of array : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("ar[%d]=",i);
scanf("%d",&ar[i]);
}
printf("Which element you want to search : ");
scanf("%d",&num);
pos=srch(n,ar,num);
if(pos!=-1)
printf("The number was found at position [%d]",pos+1);
ARKADEEP DEY (CSE2015/030) CS392
110
else
printf("The number was not found.");
getch();
return 0;
}
int srch(int n,int ar[],int num)
{
int beg=0,end=n-1,mid;
mid=(beg+end)/2;
while(beg<=end && ar[mid]!=num)
{
if(num<ar[mid])
end=mid-1;
else
beg=mid+1;
mid=(beg+end)/2;
}
if(ar[mid]==num)
return mid;
else
return -1;
}
ARKADEEP DEY (CSE2015/030) CS392
111
Q-33>Program of binary search recursive method.
#include<stdio.h> #include<conio.h> int a[10],flag=0; int binary(int num,int start, int mid, int end)
{
if(start<=end)
{
if(a[mid]==num)
{
flag=1; mid++; return mid; } else{ if(num>a[mid])
{
start=mid+1; }else
{
end=mid-1; } mid=(start+end)/2;
ARKADEEP DEY (CSE2015/030) CS392
112
binary(num,start,mid,end); }}mid++; return mid; }
int main(void)
{
int i,start,end,mid,num,ans; printf("Enter 5 Numbers\n"); for(i=0;i<=4;i++)
{
scanf("%d",&a[i]); } printf("Enter the element to be searched : "); scanf("%d",&num); start=0; end=4; mid=(start+end)/2; ans=binary(num,start,mid,end); ans++; if(flag==1) { printf("Number (%d) found at position (%d)",num,ans); } else{printf("Didnot find the number (%d)",num); } getch(); }
Q-34>interpolation search using iteration:
#include<stdio.h>
#include<conio.h>
ARKADEEP DEY (CSE2015/030) CS392
113
int Intpo_search(int a[],int size,int n)
{
int l,h,mid;
l=0;h=size-1;
while(a[l]<n && a[h]>=n)
{
mid=l+((n-a[l]*(h-l))/(a[h]-a[l]));
if(a[mid]==n)
return mid;
else if(a[mid]<n)
l=mid+1;
else
h=mid-1;
}
if(a[l]==n)
return l;
else
return -1;
}
int main()
{
int ar[20],size,n,i,j;
printf("Enter the size of array:");
scanf("%d",&size);
printf("Enter the elements in array:");
ARKADEEP DEY (CSE2015/030) CS392
114
for(i=0;i<size;i++)
scanf("%d",&ar[i]);
printf("Enter the element to be searched:");
scanf("%d",&n);
j=Intpo_search(ar,size,n);
if(j== -1)
printf("Sorry element not found...!!!");
else
printf("Element found at position %d...!!!",j+1);
getch();
return 0;
}
Q-35>interpolation search using recursion:
#include<stdio.h>
#include<conio.h>
int srch(int a[],int l,int h,int n)
{
int mid;
if(l>h)
return -1;
else
ARKADEEP DEY (CSE2015/030) CS392
115
{
mid=l+((n-a[l])*(h-l))/(a[h]-a[l]);
if(a[mid]>n)
return srch(a,l,mid-1,n);
else if(a[mid]<n)
return srch(a,mid+1,h,n);
else
return mid;
}
}
int main()
{
int i,n,ar[20],num,pos;
printf("Enter size of array : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("ar[%d]=",i);
scanf("%d",&ar[i]);
}
printf("Which element you want to search : ");
scanf("%d",&num);
pos=srch(ar,0,n-1,num);
if(pos!=-1)
printf("The number was found at position %d",pos+1);
ARKADEEP DEY (CSE2015/030) CS392
116
else
printf("The number was not found.");
getch();
return 0;
}
sorting
Q-36>bubble sort:
#include<stdio.h>
#include<conio.h>
int n;
void display(int ar[])
{
int i;
for(i=0;i<n;i++)
printf("%d\t",ar[i]);
}
ARKADEEP DEY (CSE2015/030) CS392
117
void B_sort(int a[])
{
int i,j,t,k,f=1,flag=0;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
printf("\nAfter Iteration %d:\n",f++);
display(a);
}
}
int main()
{
int ar[50],i;
printf("Enter the no of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ARKADEEP DEY (CSE2015/030) CS392
118
printf("ar[%d]=",i);
scanf("%d",&ar[i]);
}
B_sort(ar);
printf("\nThe Sorted array is:\n");
display(ar);
getch();
return 0;
}
Q-37>selection sort:
#include<stdio.h>
#include<conio.h>
void show(int,int[]);
void slctsrt(int,int[]);
int main()
{
int i,d[100],n,;
printf("\nEnter how many no:");
ARKADEEP DEY (CSE2015/030) CS392
119
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter %d no:",i+1);
scanf("%d",&d[i]);
}
slctsrt(n,d);
getch();
return 0;
}
void slctsrt(int n,int d[])
{
int i,j,t,loc,min;
for(i=0;i<n-1;i++)
{
min=d[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(d[j]<min)
{
min=d[j];
loc=j;
}
}
ARKADEEP DEY (CSE2015/030) CS392
120
if(loc!=i)
{
t=d[i];
d[i]=d[loc];
d[loc]=t;
}
printf("\nAfter %d iteration",i+1);
show(n,d);
}
}
void show(int n,int d[])
{
int i;
printf("\nAfter sorted the array become:");
for(i=0;i<n;i++)
printf("\t%d",d[i]);
}
ARKADEEP DEY (CSE2015/030) CS392
121
Q-38>insertion sort:
#include<stdio.h>
#include<conio.h>
void display(int [],int);
void insertion(int [],int);
int main()
{
int a[20],n,i;
printf("\nenter the no. of elements:");
scanf("%d",&n);
printf("\nthe elements are:");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d",&a[i]);
ARKADEEP DEY (CSE2015/030) CS392
122
}
printf("\nbefore sorting the array is");
display(a,n);
insertion(a,n);
printf("\nafter sorting the array is:");
display(a,n);
getch();
return 0;
}
void display(int a[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
}
void insertion(int a[],int n)
{
int y,i,k;
for(k=1;k<n;k++)
{
y=a[k];
for(i=k-1;i>=0&&y<a[i];i--)
{
ARKADEEP DEY (CSE2015/030) CS392
123
a[i+1]=a[i];
}
a[i+1]=y;
}
}
Q-39>Merge sort:
#include<stdio.h>
#include<conio.h>
#define max 20
void display(int a[],int n)
{
int i;
printf("\nthe sorted array is...\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
ARKADEEP DEY (CSE2015/030) CS392
124
}
void merge(int a[],int temp[],int low1,int high1,int low2,int high2)
{
int i,j,k;
i=k=low1;
j=low2;
while((i<=high1)&&(j<=high2))
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=high1)
temp[k++]=a[i++];
while(j<=high2)
temp[k++]=a[j++];
}
void copy(int a[],int temp[],int l,int u)
{
int i;
for(i=l;i<=u;i++)
a[i]=temp[i];
}
ARKADEEP DEY (CSE2015/030) CS392
125
void mrg_srt(int a[],int l,int u)
{
int temp[max],mid;
if(l<u)
{
mid=(l+u)/2;
mrg_srt(a,l,mid);
mrg_srt(a,mid+1,u);
merge(a,temp,l,mid,mid+1,u);
copy(a,temp,l,u);
}
}
int main()
{
int ar[max],i,n;
printf("Enter no of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("ar[%d]=",i);
scanf("%d",&ar[i]);
}
mrg_srt(ar,0,n-1);
display(ar,n);
getch();
ARKADEEP DEY (CSE2015/030) CS392
126
return 0; }
Q-40>Radix sort:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void display(int [],int);
void radix(int [],int);
int main()
{
int a[20],n,i;
printf("\nenter the no. of elements:");
scanf("%d",&n);
printf("\nthe elements are:");
for(i=0;i<n;i++)
{
ARKADEEP DEY (CSE2015/030) CS392
127
printf("a[%d]=",i);
scanf("%d",&a[i]);
}
printf("\nbefore sorting the array is");
display(a,n);
radix(a,n);
printf("\nafter sorting the array is:");
display(a,n);
getch();
return 0;
}
void display(int a[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
}
void radix(int a[],int n)
{
int i,j,k,b[20][40],d[40],count=0,c,max,p,z;
max=a[0];
for(i=0;i<n;i++)
{
ARKADEEP DEY (CSE2015/030) CS392
128
if(a[i]>max)
{
max=a[i];
}
}
while(max!=0)
{
count++;
max=max/10;
}
for(i=0;i<count;i++)
{
for(k=0;k<10;k++)
{
d[k]=0;
}
p=0;
for(j=0;j<n;j++)
{
z=pow(10,i);
c=((a[j]/z)%10);
b[c][d[c]++]=a[j];
}
for(k=0;k<10;k++)
ARKADEEP DEY (CSE2015/030) CS392
129
{
for(j=0;j<d[k];j++)
a[p++]=b[k][j];
} } }
Q-41>Quick sort:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void partition(int ele[],int lb,int ub,int *p)
{
ARKADEEP DEY (CSE2015/030) CS392
130
int down,up,a,t;
a = ele[lb];
down = lb;
up = ub;
while( down < up )
{
while( ele[down] <= a && down <=ub )
down++;
while( ele[up] > a )
up--;
if( down < up )
{
t = ele[down];
ele[down] = ele[up];
ele[up] = t;
}
}
ele[lb] = ele[up];
ele[up] = a;
*p = up;
}
void qsort(int ele[],int lb,int ub)
{
ARKADEEP DEY (CSE2015/030) CS392
131
int pos;
if( lb < ub )
{
partition( ele , lb , ub , &pos );
qsort( ele , lb , pos-1 );
qsort( ele , pos+1 , ub );
}
}
int main()
{
int *ele;
int i,n;
printf("\n Enter the number of eles : ");
scanf("%d",&n);
ele = (int *)malloc( sizeof(int) * n ); printf("\n Enter the elements now : ");
for( i=0 ; i<n ; i++ )
scanf("%d",&ele[i]);
qsort( ele , 0 , n-1 );
printf("\n After sorting : ");
for( i=0 ; i<n ; i++ )
printf("%d ",ele[i]);
getch();
return 0;
ARKADEEP DEY (CSE2015/030) CS392
132
}
Q-42>Shell sort:
#include<stdio.h>
#include<conio.h>
void display(int [],int);
void shell(int [],int);
int main()
{
int a[20],n,i;
printf("\nenter the no. of elements:");
scanf("%d",&n);
printf("\nthe elements are:");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d",&a[i]);
}
printf("\nbefore sorting the array is");
display(a,n);
shell(a,n);
ARKADEEP DEY (CSE2015/030) CS392
133
printf("\nafter sorting the array is:");
display(a,n);
getch();
return 0;
}
void display(int a[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
}
void shell(int a[],int n)
{
int m,temp,i,j;
for(m=n/2;m>0;m/=2)
{
for(j=m;j<n;j++)
{
for(i=j-m;i>=0;i-=m)
{
if(a[i+m]>=a[i])
break;
else
ARKADEEP DEY (CSE2015/030) CS392
134
{
temp=a[i];
a[i]=a[i+m];
a[i+m]=temp;
}
}
}
}
}
Q-43>Heap sort:
#include<stdio.h>
#include<conio.h>
ARKADEEP DEY (CSE2015/030) CS392
135
#include<malloc.h>
void adjust(int ele[],int i,int n)
{
int j,item;
item = ele[i];
j = 2 * i + 1;
while( j <= n-1 )
{
if( j < n-1 && ele[j] < ele[j+1] )
j = j + 1;
if( item >= ele[j] )
break;
ele[ (j-1)/2 ] = ele[j];
j = 2 * j + 1;
}
ele[ (j-1)/2 ] = item;
}
void heapify( int ele[] , int n )
{
int i;
for( i=(n-2)/2 ; i>=0 ; i-- )
adjust( ele , i , n );
}
void hsort(int ele[],int n)
ARKADEEP DEY (CSE2015/030) CS392
136
{
int i,t;
heapify( ele , n );
for( i=n-1 ; i>=1 ; i-- )
{
t = ele[i];
ele[i] = ele[0];
ele[0] = t;
adjust( ele , 0 , i );
}
}
int main()
{
int *ele;
int i,n;
printf("\n Enter the number of eles : ");
scanf("%d",&n);
ele = (int *)malloc( sizeof(int) * n );
printf("\n Enter the elements now : ");
for( i=0 ; i<n ; i++ )
scanf("%d",&ele[i]);
hsort( ele , n );
printf("\n After sorting : ");
for( i=0 ; i<n ; i++ )
printf("%d ",ele[i]);
ARKADEEP DEY (CSE2015/030) CS392
137
getch();
return 0;
}
tree
Q-44>Program to implement binary search tree.
#include<stdio.h> #include<stdlib.h>
struct tree { int info; struct tree *left; struct tree *right;
};
ARKADEEP DEY (CSE2015/030) CS392
138
struct tree *insert(struct tree *,int);
void inorder(struct tree *);
void postorder(struct tree *);
void preorder(struct tree *);
void findroot(struct tree *);
struct tree *del(struct tree *,int);
int main(void)
{
struct tree *root; int ch,item,item_no; root=NULL; do { do { printf("\n\n\t\t\tMENU"); printf("\n\t######################################"); printf("\n\n\t1. Binary Search Tree Insertion "); printf("\n\t2. Binary Search Tree Deletion "); printf("\n\t3. Inorder Traversal of Binary Search Tree"); printf("\n\t4. Postorder Traversal of Binary Search Tree"); printf("\n\t5. Preorder Traversal of Binary Search Tree"); printf("\n\t6. Find Root "); printf("\n\t7. Exit\n\n"); printf("\nEnter the Choice : "); scanf(" %d",&ch); if(ch<1 || ch>7) { printf("\nInvalid choice: Try again!!!"); } }while (ch<1 || ch>7); switch(ch) {
case 1: printf("\nEnter the New Element: "); scanf("%d", &item);
ARKADEEP DEY (CSE2015/030) CS392
139
root=insert(root,item); break; case 2: if(root!=NULL) { printf("\nEnter the Element to be Deleted: "); scanf(" %d",&item_no);
root=del(root,item_no); printf("The Binary Search Tree is now:\n"); inorder(root); } else { printf("\nBinary Search Tree is Empty!!!\n"); } break; case 3: if(root!=NULL) { printf("\nInorder Traversal of Binary Search Tree is: "); inorder(root); } else { printf("\nBinary Search Tree is Empty!!!\n"); } break; case 4: if(root!=NULL) { printf("\nPostorder Traversal of Binary Search Tree is: "); postorder(root); }else
{ printf("\nBinary Search Tree is Empty!!!\n"); } break; case 5 : if(root!=NULL)
ARKADEEP DEY (CSE2015/030) CS392
140
{ printf("\nPreorder Traversal of Binary Search Tree is: "); preorder(root); } else { printf("\nBinary Search Tree is Empty!!!\n"); } break; case 6: findroot(root); break; default: printf("\nProgram Terminating\n\n"); } } while(ch !=7); return(0); }
struct tree *insert(struct tree *root, int x)
{
if(!root)
{
root=(struct tree*)malloc(sizeof(struct tree)); root->info=x; root->left=NULL; root->right=NULL; return(root); } if(root->info>x) { root->left=insert(root->left,x); } else { if(root->info<x) { root->right=insert(root->right,x); } } return(root); }
ARKADEEP DEY (CSE2015/030) CS392
141
void inorder(struct tree *root) { if(root!=NULL) { inorder(root->left); printf(" %d",root->info); inorder(root->right); } return; }
void postorder(struct tree *root) { if(root!=NULL) { postorder(root->left); postorder(root->right); printf(" %d",root->info); } return; }
void preorder(struct tree *root) { if(root!=NULL) { printf(" %d",root->info); preorder(root->left); preorder(root->right); } return; }
void findroot(struct tree *root) { if(root!=NULL)
{ printf("\nRoot is %d\n",root->info); } else { printf("\nBinary Search Tree is Empty!!!\n"); } }
ARKADEEP DEY (CSE2015/030) CS392
142
struct tree *del(struct tree *ptr,int x) { struct tree *p1,*p2; if(!ptr) { printf("\nElement not Found!!!\n"); return(ptr); } else { if(ptr->info<x) { ptr->right=del(ptr->right,x); } else if(ptr->info>x) { ptr->left=del(ptr->left,x); return ptr; } else { if(ptr->info==x) { if(ptr->left==ptr->right) { free(ptr); return(NULL); } else if(ptr->left==NULL) { p1=ptr->right; free(ptr); return p1; } else if(ptr->right==NULL) { p1=ptr->left; free(ptr); return p1;
ARKADEEP DEY (CSE2015/030) CS392
143
} else { p1=ptr->right; p2=ptr->right; while(p1->left != NULL) { p1=p1->left;
}
p1->left=ptr->left;
free(ptr);
return p2;
} } } }
return(ptr);
}
ARKADEEP DEY (CSE2015/030) CS392
144
Q-45>BST traverse(inorder,preorder,postorder)using recursion:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
struct bst
{
struct bst *lc;
int d;
struct bst *rc;
}*bt;
void insert(struct bst **,int);
ARKADEEP DEY (CSE2015/030) CS392
145
void inorder(struct bst *);
void preorder(struct bst *);
void postorder(struct bst *);
int n,i,num;
int main()
{
bt='\0';
printf("Enter the number of items to be inserted: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the data: ");
scanf("%d",&num);
insert(&bt,num);
}
printf("\nIn-order Traversal: ");
inorder(bt);
printf("\nPre-order Traversal: ");
preorder(bt);
printf("\nPost-order Traversal:");
postorder(bt);
getch();
return 0;
}
void insert(struct bst **sr,int num)
ARKADEEP DEY (CSE2015/030) CS392
146
{
if(*sr=='\0')
{
*sr=(struct bst *)malloc(sizeof(struct bst));
(*sr)->lc='\0';
(*sr)->d=num;
(*sr)->rc='\0';
}
else
{
if(num<(*sr)->d)
insert(&((*sr)->lc),num);
else
insert(&((*sr)->rc),num);
}
}
void inorder(struct bst *sr)
{
if(sr!=NULL)
{
inorder(sr->lc);
printf("%d ",sr->d);
inorder(sr->rc);
}
else
ARKADEEP DEY (CSE2015/030) CS392
147
return;
}
void preorder(struct bst *sr)
{
if(sr!=NULL)
{
printf("%d ",sr->d);
// traverse till lc is not NULL
preorder(sr->lc);
// traverse till rc is not NULL
preorder(sr->rc);
}
else
return;
}
void postorder(struct bst *sr)
{
if(sr!=NULL)
{
postorder(sr->lc);
postorder(sr->rc);
printf("%d ",sr->d);
}
else
return;
ARKADEEP DEY (CSE2015/030) CS392
148
}
Q-46>.Program to implement Threaded Binary Search Tree
/* C program to implement Threaded binary tree */
# include <stdio.h> # include <malloc.h> #define infinity 9999
typedef enum {thread,link} boolean; struct node *in_succ(struct node *p); struct node *in_pred(struct node *p);
struct node { struct node *left_ptr; boolean left; int info; boolean right;
ARKADEEP DEY (CSE2015/030) CS392
149
struct node *right_ptr; }*head=NULL;
int main() { int choice,num; insert_head(); while(1) { printf("\n"); printf("1.Insert\n"); printf("2.Inorder Traversal\n"); printf("3.Quit\n"); printf("Enter your choice : "); scanf("%d",&choice);
switch(choice) { case 1: printf("Enter the number to be inserted : "); scanf("%d",&num); insert(num); break; case 2: inorder(); break; case 3: exit(); default: printf("Wrong choice\n"); }/*End of switch */
}/*End of while */ }/*End of main function*/
ARKADEEP DEY (CSE2015/030) CS392
150
int insert_head() { struct node *tmp; head=(struct node *)malloc(sizeof(struct node)); head->info= infinity;
head->left=thread; head->left_ptr=head; head->right=link; head->right_ptr=head; }/*End of insert_head()*/
int find(int item,struct node **par,struct node **loc) { struct node *ptr,*ptrsave; if(head->left_ptr==head) /* If tree is empty*/ { *loc=NULL; *par=head; return; } if(item==head->left_ptr->info) /* item is at head->left_ptr */ { *loc=head->left_ptr; *par=head; return; } ptr=head->left_ptr; while(ptr!=head) { ptrsave=ptr; if( item < ptr->info ) { if(ptr->left==link) ptr=ptr->left_ptr; else break; } else
ARKADEEP DEY (CSE2015/030) CS392
151
if(item > ptr->info ) { if(ptr->right==link) ptr=ptr->right_ptr; else break; } if(item==ptr->info) { *loc=ptr; *par=ptrsave; return; } }/*End of while*/ *loc=NULL; /*item not found*/ *par=ptrsave; }/*End of find()*/
/* Creating threaded binary search tree */
int insert(int item) { struct node *tmp,*parent,*location;
find(item,&parent,&location);
if(location!=NULL) { printf("Item already present"); return; }
ARKADEEP DEY (CSE2015/030) CS392
152
tmp=(struct node *)malloc(sizeof(struct node)); tmp->info=item; tmp->left=thread; tmp->right=thread;
if(parent==head) /*tree is empty*/ { head->left=link; head->left_ptr=tmp; tmp->left_ptr=head; tmp->right_ptr=head; } else if( item < parent->info ) { tmp->left_ptr=parent->left_ptr; tmp->right_ptr=parent; parent->left=link; parent->left_ptr=tmp; } else { tmp->left_ptr=parent; tmp->right_ptr=parent->right_ptr; parent->right=link; parent->right_ptr=tmp; }
}/*End of insert()*/
/* Finding succeeder */
struct node *in_succ(struct node *ptr) { struct node *succ;
ARKADEEP DEY (CSE2015/030) CS392
153
if(ptr->right==thread) succ=ptr->right_ptr; else { ptr=ptr->right_ptr; while(ptr->left==link) ptr=ptr->left_ptr; succ=ptr; } return succ; }/*End of in_succ()*/
/* Finding predecessor */
struct node *in_pred(struct node *ptr) { struct node *pred; if(ptr->left==thread)
pred=ptr->left_ptr; else {
ptr=ptr->left_ptr; while(ptr->right==link)
ptr=ptr->right_ptr; pred=ptr; } return pred; }/*End of in_pred()*/
/* Displaying all nodes */
inorder() {
struct node *ptr; if(head->left_ptr==head)
{ printf("Tree is empty"); return; }
ptr=head->left_ptr;
ARKADEEP DEY (CSE2015/030) CS392
154
/*Find the leftmost node and traverse it */
while(ptr->left==link)
ptr=ptr->left_ptr; printf("%d ",ptr->info);
while( 1 ) {
ptr=in_succ(ptr); if(ptr==head) /*If last node reached */
break; printf("%d ",ptr->info); } /*End of while*/
}/*End of inorder()*/
ARKADEEP DEY (CSE2015/030) CS392
155
Q-47>Program to implement AVL tree.
#include<stdio.h> #include<stdlib.h> typedef struct node {
int data; struct node *left,*right; int ht; }node;
node *insert(node *,int); node *Delete(node *,int); void preorder(node *); void inorder(node *); int height( node *); node *rotateright(node *); node *rotateleft(node *); node *RR(node *); node *LL(node *); node *LR(node *); node *RL(node *); int BF(node *); int main() { node *root=NULL; int x,n,i,op; do { printf("\n1)Create:"); printf("\n2)Insert:"); printf("\n3)Delete:"); printf("\n4)Print:"); printf("\n5)Quit:"); printf("\n\nEnter Your Choice:"); scanf("%d",&op);
ARKADEEP DEY (CSE2015/030) CS392
156
switch(op) { case 1: printf("\nEnter no. of elements:"); scanf("%d",&n); printf("\nEnter tree data:"); root=NULL; for(i=0;i<n;i++) { scanf("%d",&x); root=insert(root,x); } break; case 2: printf("\nEnter a data:"); scanf("%d",&x); root=insert(root,x); break; case 3: printf("\nEnter a data:"); scanf("%d",&x); root=Delete(root,x); break; case 4: printf("\nPreorder sequence:\n"); preorder(root); printf("\n\nInorder sequence:\n"); inorder(root); printf("\n"); break; } } while(op!=5); return 0; } node * insert(node *T,int x) { if(T==NULL) { T=(node*)malloc(sizeof(node)); T->data=x;
ARKADEEP DEY (CSE2015/030) CS392
157
T->left=NULL; T->right=NULL; } else if(x > T->data) // insert in right subtree { T->right=insert(T->right,x); if(BF(T)==-2) if(x>T->right->data) T=RR(T); else T=RL(T); } else if(x<T->data) { T->left=insert(T->left,x); if(BF(T)==2) if(x < T->left->data) T=LL(T); else T=LR(T); } T->ht=height(T); return(T); } node * Delete(node *T,int x) { node *p;
if(T==NULL) {
return NULL; }
else if(x > T->data) // insert in right subtree { T->right=Delete(T->right,x); if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T); else
ARKADEEP DEY (CSE2015/030) CS392
158
T=LR(T); }
else if(x<T->data)
{
T->left=Delete(T->left,x); if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T); else
T=RL(T); }
else
{ //data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right; while(p->left!= NULL)
p=p->left; T->data=p->data; T->right=Delete(T->right,p->data); if(BF(T)==2)//Rebalance during windup
if(BF(T->left)>=0)
T=LL(T); else T=LR(T); } else
return(T->left); }
ARKADEEP DEY (CSE2015/030) CS392
159
T->ht=height(T); return(T); } int height(node *T)
{
int lh,rh; if(T==NULL)
return(0);
if(T->left==NULL)
lh=0; else lh=1+T->left->ht; if(T->right==NULL) rh=0; else rh=1+T->right->ht; if(lh>rh)
return(lh); return(rh); }
node * rotateright(node *x) {
node *y; y=x->left; x->left=y->right; y->right=x; x->ht=height(x); y->ht=height(y); return(y); } node * rotateleft(node *x) {
node *y; y=x->right; x->right=y->left; y->left=x; x->ht=height(x);
ARKADEEP DEY (CSE2015/030) CS392
160
y->ht=height(y); return(y); } node * RR(node *T) { T=rotateleft(T); return(T); } node * LL(node *T) { T=rotateright(T); return(T); } node * LR(node *T) { T->left=rotateleft(T->left); T=rotateright(T);
return(T); }
node * RL(node *T) {
T->right=rotateright(T->right); T=rotateleft(T); return(T); }
int BF(node *T) {
int lh,rh; if(T==NULL)
return(0); if(T->left==NULL)
lh=0; else
lh=1+T->left->ht; if(T->right==NULL)
rh=0; else
rh=1+T->right->ht; return(lh-rh); }
void preorder(node *T) {
ARKADEEP DEY (CSE2015/030) CS392
161
if(T!=NULL) {
printf("%d(Bf=%d)",T->data,BF(T)); preorder(T->left); preorder(T->right); } }
void inorder(node *T) {
if(T!=NULL)
{
inorder(T->left); printf("%d(Bf=%d)",T->data,BF(T)); inorder(T->right); } }
ARKADEEP DEY (CSE2015/030) CS392
162
grAPh
Q-48 & Q-49> Implementation of bfs & dfs:
#include<stdio.h>
int q[ 20 ], top = -1, front = -1, rear = -1, a[ 20 ][ 20 ], vis[ 20 ], stack[ 20 ];
int delete();
void add ( int item );
void bfs( int s, int n );
void dfs( int s, int n );
void push( int item );
int pop();
int main()
{
int n, i, s, ch, j;
char c, dummy;
printf( "ENTER THE NUMBER VERTICES:" );
scanf( "%d", &n );
for ( i = 1;i <= n;i++ )
{
for ( j = 1;j <= n;j++ )
{
printf( "ENTER 1 IF %d HAS A NODE WITH %d ELSE 0:", i, j );
scanf( "%d", &a[ i ][ j ] );
}
ARKADEEP DEY (CSE2015/030) CS392
163
}
printf( "THE ADJACENCY MATRIX IS\n:" );
for ( i = 1;i <= n;i++ )
{
for ( j = 1;j <= n;j++ )
{
printf( " %d", a[ i ][ j ] );
}
printf( "\n" );
}
do
{
for ( i = 1;i <= n;i++ )
vis[ i ] = 0;
printf( "\nMENU" );
printf( "\n1.B.F.S.." );
printf( "\n2.D.F.S.." );
printf( "\nENTER YOUR CHOICE:" );
scanf( "%d", &ch );
printf( "ENTER THE SOURCE VERTEX :" );
scanf( "%d", &s );
switch ( ch )
{
case 1:
ARKADEEP DEY (CSE2015/030) CS392
164
bfs( s, n );
break;
case 2:
dfs( s, n );
break;
}
printf( "\nDO U WANT TO CONTINUE(Y/N) ? " );
scanf( "%c", &dummy );
scanf( "%c", &c );
}
while ( ( c == 'y' ) || ( c == 'Y' ) );
getch();
return 0;
}
void bfs( int s, int n )
{
int p, i;
add
( s );
vis[ s ] = 1;
p = delete();
if ( p != 0 )
printf( " %d", p );
while ( p != 0 )
{
ARKADEEP DEY (CSE2015/030) CS392
165
for ( i = 1;i <= n;i++ )
if ( ( a[ p ][ i ] != 0 ) && ( vis[ i ] == 0 ) )
{
add
( i );
vis[ i ] = 1;
}
p = delete();
if ( p != 0 )
printf( " %d ", p );
}
for ( i = 1;i <= n;i++ )
if ( vis[ i ] == 0 )
bfs( i, n );
}
void add
( int item )
{
if ( rear == 19 )
printf( "QUEUE FULL" );
else
{
if ( rear == -1 )
{
q[ ++rear ] = item;
ARKADEEP DEY (CSE2015/030) CS392
166
front++;
}
else
q[ ++rear ] = item;
}
}
int delete()
{
int k;
if ( ( front > rear ) || ( front == -1 ) )
return ( 0 );
else
{
k = q[ front++ ];
return ( k );
}
}
void dfs( int s, int n )
{
int i, k;
push( s );
vis[ s ] = 1;
k = pop();
if ( k != 0 )
printf( " %d ", k );
ARKADEEP DEY (CSE2015/030) CS392
167
while ( k != 0 )
{
for ( i = 1;i <= n;i++
if ( ( a[ k ][ i ] != 0 ) && ( vis[ i ] == 0 ) )
{
push( i );
vis[ i ] = 1;
}
k = pop();
if ( k != 0 )
printf( " %d ", k );
}
for ( i = 1;i <= n;i++ )
if ( vis[ i ] == 0 )
dfs( i, n );
}
void push( int item )
{
if ( top == 19 )
printf( "Stack overflow " );
else
stack[ ++top ] = item;
}
int pop()
{
ARKADEEP DEY (CSE2015/030) CS392
168
int k;
if ( top == -1 )
return ( 0 );
else
{
k = stack[ top-- ];
return ( k );
} }
Additional Lab Exercise
ArrAy
Q-50> creation of 2d array with different column size for each row:
#include<stdio.h>
ARKADEEP DEY (CSE2015/030) CS392
169
#include<conio.h>
#include<malloc.h>
void dynamic_array (int**,int);
void display(int**,int,int[]);
int main()
{
int **a,row,column;
printf("\n enter how many row:");
scanf("%d",& row);
a=(int **)malloc(sizeof(int)*row);
dynamic_array(a,row);
getch();
return 0;
}
void dynamic_array(int **a,int row)
{
int i,j,column,b[100],p=0;
for(i=0;i<row;i++)
{
printf("\n how many column for %d no row:",i+1);
scanf("%d",&column);
a[i]=(int*)malloc(sizeof(int)*column);
b[p++]=column;
}
p=0;
ARKADEEP DEY (CSE2015/030) CS392
170
for(i=0;i<row;i++)
{
for(j=0;j<b[p];j++)
{
printf("a[%d][%d]=",i+1,j+1);
scanf("%d",&a[i][j]);
}
p++;
}
display(a,row,b);
}
void display(int **a,int row,int b[])
{
int i,j,k=0;
printf("\n the array elements are:\n");
for(i=0;i<row;i++)
{
for(j=0;j<b[k];j++)
{
printf("a[%d][%d]=%d\t",i+1,j+1,a[i][j]);
}
printf("\n");
k++;
}
}
ARKADEEP DEY (CSE2015/030) CS392
171
Q-51>Dynamic Memory Allocation of 3d array :
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void three_darray(int ***,int);
void display(int ***,int,int,int);
int main()
{
int ***a,x;
printf("\n the 3-d array is look like:->a[x][y][z]");
printf("\n enter the value of x:");
ARKADEEP DEY (CSE2015/030) CS392
172
scanf("%d",&x);
a=(int***)malloc(sizeof(int)*x);
three_darray(a,x);
getch();
return 0;
}
void three_darray(int ***a,int x)
{
int i,j,k,y,z;
printf("\n enter the value of y:");
scanf("%d",&y);
for(i=0;i<x;i++)
{
a[i]=(int**)malloc(sizeof(int)*y);
}
printf("\n enter the value of k:");
scanf("%d",&z);
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
a[i][j]=(int *)malloc(sizeof(int)*z);
}
}
for(i=0;i<x;i++)
ARKADEEP DEY (CSE2015/030) CS392
173
{
for(j=0;j<y;j++)
{
for(k=0;k<z;k++)
{
printf("a[%d][%d][%d]=",i+1,j+1,k+1);
scanf("%d",&a[i][j][k]);
}
}
}
display(a,x,y,z);
}
void display(int ***a,int x,int y,int z)
{
int i,j,k;
printf("\n the 3d array is:->\n");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
for(k=0;k<z;k++)
{
printf("a[%d][%d][%d]=%d\t",i+1,j+1,k+1,a[i][j][k]);
}
}
ARKADEEP DEY (CSE2015/030) CS392
174
printf("\n");
}
}
Q-52>sparce matrix addition:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void add(int sp1[][3],int sp2[][3],int r1,int r2)
{
int i,j,k,a,b,temp[20][3];
i=j=k=1;
if(sp1[0][0]!=sp2[0][0] || sp1[0][1]!=sp2[0][1])
{
printf("Addition not possible");
ARKADEEP DEY (CSE2015/030) CS392
175
exit(20);
}
while(i<r1 && j<r2)
{
if(sp1[i][0]==sp2[j][0] && sp1[i][1]==sp2[j][1])
{
temp[k][0]=sp1[i][0];
temp[k][1]=sp1[i][1];
temp[k][2]=sp1[i][2]+sp2[j][2];
i++;j++;k++;
}
else if(sp1[i][0]==sp2[j][0] && sp1[i][1]!=sp2[j][1])
{
if(sp1[i][1]<sp2[j][1])
{
temp[k][0]=sp1[i][0];
temp[k][1]=sp1[i][1];
temp[k][2]=sp1[i][2];
k++;i++;
}
else
{
temp[k][0]=sp2[j][0];
temp[k][1]=sp2[j][1];
temp[k][2]=sp2[j][2];
ARKADEEP DEY (CSE2015/030) CS392
176
k++;j++;
}
}
else if(sp1[i][0]<sp2[j][0])
{
temp[k][0]=sp1[i][0];
temp[k][1]=sp1[i][1];
temp[k][2]=sp1[i][2];
k++;i++;
}
else
{
temp[k][0]=sp2[j][0];
temp[k][1]=sp2[j][1];
temp[k][2]=sp2[j][2];
k++;j++;
}
}
while(i<r1)
{
temp[k][0]=sp1[i][0];
temp[k][1]=sp1[i][1];
temp[k][2]=sp1[i][2];
k++;i++;
}
ARKADEEP DEY (CSE2015/030) CS392
177
while(j<r2)
{
temp[k][0]=sp2[j][0];
temp[k][1]=sp2[j][1];
temp[k][2]=sp2[j][2];
k++;j++;
}
temp[0][0]=sp1[0][0];
temp[0][1]=sp1[0][1];
temp[0][2]=k-1;
printf("Addition Result:\n");
for(a=0;a<k;a++)
{
for(b=0;b<3;b++)
printf("%d ",temp[a][b]);
printf("\n");
}
}
int main()
{
int a[10][3],b[10][3],i,j,r1,r2;
printf("Enter no of rows in 1st matrix:");
scanf("%d",&r1);
printf("Enter eles in 1st matrix:\n");
ARKADEEP DEY (CSE2015/030) CS392
178
for( i=0 ; i<r1 ; i++ )
for( j=0 ; j<3 ; j++ )
scanf("%d",&a[i][j]);
printf("Enter no of rows in 2nd matrix:");
scanf("%d",&r2);
printf("Enter the eles in 2nd matrix:\n");
for( i=0 ; i<r2 ; i++ )
for( j=0 ; j<3 ; j++ )
scanf("%d",&b[i][j]);
add(a,b,r1,r2);
getch();
return 0;
}
Q-53>.Multiplication of sparse matrix.
#include<conio.h> #include<stdio.h> #include<stdlib.h> #define MAX 20
ARKADEEP DEY (CSE2015/030) CS392
179
void print_sparse(int b[MAX][3]); void read_sparse(int b[MAX][3]); void multiply(int b1[MAX][3],int b2[MAX][3],int b3[MAX][3]); void Fast_transpose(int B1[MAX][3],int B2[MAX][3]); int main(void) { int b1[MAX][3],b2[MAX][3],b3[MAX][3]; read_sparse(b1); read_sparse(b2); multiply(b1,b2,b3); print_sparse(b3); getch(); } void multiply(int b1[MAX][3],int b2[MAX][3],int b3[MAX][3]) { int b22[MAX][3]; int i,j,k,B1rno,B2colno,i1,sum,t1,t2; t1=b1[0][2];t2=b2[0][2]; if(b1[0][1]!=b2[0][0]) { printf("\n can not multiply"); exit(0); } Fast_transpose(b2,b22); /* b1 in row major form and b2 in column major form ,as for multiplication,dot product of a row of b1 with column of b2 is taken */ k=1; //index for b3 i=1; while(i<=t1) { i1=i; j=1; while(j<=t2) { B1rno=b1[i][0];
ARKADEEP DEY (CSE2015/030) CS392
180
B2colno=b22[j][0]; sum=0;
while(i<=t1 && j<=t2 && B1rno==b1[i][0] && B2colno==b22[j][0]) { if(b1[i][1]==b22[j][1]) { sum=sum+b1[i][2]*b22[j][2]; i++;j++; } else if(b1[i][1]<b22[j][1]) i++; else j++; }
if(sum!=0) { b3[k][0]=B1rno; b3[k][1]=B2colno; b3[k][2]=sum; k++; } if(j<=t2) i=i1; while(B2colno==b22[j][0] && j<=t2) j++; } while(B1rno==b1[i][0] && i<=t1) i++; } b3[0][0]=b1[0][0]; b3[0][1]=b22[0][0]; b3[0][2]=k-1; }
ARKADEEP DEY (CSE2015/030) CS392
181
void print_sparse(int b[MAX][3]) { int i,n; n=b[0][2]; //no of 3-triples printf("\nrows = %d\tcolumns = %d",b[0][0],b[0][1]); printf("\n"); for(i=0; i<=n;i++) printf("%d\t%d\t%d\n",b[i][0],b[i][1],b[i][2]); } void read_sparse(int b[MAX][3]) { int i,t; printf("\nEnter size of the matrix:"); scanf("%d%d",&b[0][0],&b[0][1]); printf("\nEnter no. of non-zero elements:"); scanf("%d",&t); b[0][2]=t;
for(i=1;i<=t;i++) { printf("\n Enter the next triple(row,column,value) :"); scanf("%d%d%d",&b[i][0],&b[i][1],&b[i][2]); } } void Fast_transpose(int B1[MAX][3],int B2[MAX][3]) { int m,n,t,i,col_num,location; int total[MAX],index[MAX]; m=B1[0][0];n=B1[0][1];t=B1[0][2]; B2[0][0]=n; B2[0][1]=m; B2[0][2]=t; for(i=0;i<n;i++) total[i]=0; for(i=1;i<=t;i++) { col_num=B1[i][1]; total[col_num]++;
} index[0]=1; for(i=1;i<n;i++) index[i]=index[i-1]+total[i-1];
ARKADEEP DEY (CSE2015/030) CS392
182
for(i=1;i<=t;i++) { col_num=B1[i][1]; location=index[col_num]; index[col_num]++; B2[location][0]=B1[i][1]; B2[location][1]=B1[i][0]; B2[location][2]=B1[i][2]; } }
recursion
Q-54>Factorial using tail recursion:
#include<stdio.h>
#include<conio.h>
long int fact(int);
ARKADEEP DEY (CSE2015/030) CS392
183
long int fact1(int,long int);
int main()
{
int n;
long int c;
printf("\n enter a number(must be a positive integer):");
scanf("%d",&n);
c=fact(n);
printf("\n the factorial of %d is->%ld",n,c);
getch();
return 0;
}
long int fact(int n)
{
return fact1(n,1);
}
long int fact1(int n,long int r)
{
if(n==0)
return 1;
else if(n==1)
return r;
else
return fact1(n-1,n*r);
}
ARKADEEP DEY (CSE2015/030) CS392
184
Q-55>Gcd using tail recursion:
#include<stdio.h>
#include<conio.h>
int gcd(int,int);
int gcd1(int,int);
int main()
{
int a,b,c;
printf("\n enter two number:");
scanf(" %d %d",&a,&b);
c=gcd(a,b);
printf("\n the gcd of %d and %d is->%d",a,b,c);
getch();
return 0;
}
int gcd(int a,int b)
{
return gcd1(a,b);
}
int gcd1(int a,int b)
{
if(a<b)
ARKADEEP DEY (CSE2015/030) CS392
185
gcd(b,a);
if(a%b==0)
return b;
else
return gcd1(b,a%b);
}
Q-56>implement 8 queen puzzle:
#include <stdio.h>
#include<conio.h>
#define N 8
int Chess(char Arr[N][N] , int row);
int check(char Arr[N][N],int row,int line);
//double count;
int main()
{
char chess[N][N]={0};
Chess(chess,0);/* The call to the function*/
{
int i,y;
ARKADEEP DEY (CSE2015/030) CS392
186
for(i=0;i<N;++i)/*prints the result*/
{
printf("\n\t\t\t");
for(y=0;y<N;++y)
{
if(chess[i][y]==0)
printf("x ");
else
printf("%c ",chess[i][y]);
}
}
}
printf("\n");
getch();
return 0;
}
int Chess(char Arr[N][N] , int row)
{
int line=0;
if(row==N)
return 1;
while(line < N)
{
if(check(Arr,row,line)) /*check the row*/
{
ARKADEEP DEY (CSE2015/030) CS392
187
Arr[row][line]='Q'; /*puts a queen on the board*/
if(Chess(Arr,row+1))/*the recursion*/
return 1;
Arr[row][line]=0;/*clears the last change if*/
}/*returned 0 from the recursion*/
line++;
}
return 0;
}
int check(char Arr[N][N],int row,int line)
{/*check just the left size of the board*/
int r,l;
r=row;
l=line;
while(r >= 0 && l >= 0)
{
if(Arr[r][l]=='Q')
return 0;
--r;
--l;
}
l=line;
r=row;
while(l < N && r >= 0)
{
ARKADEEP DEY (CSE2015/030) CS392
188
if(Arr[r][l]=='Q')
return 0;
++l;
--r;
}
l=line;
r=row;
while(r >= 0)
{
if(Arr[r][l]=='Q')
return 0;
--r;
}
return 1;
}
Doubly circulAr link list
Q-57>creation, count, display of a doubly circular link list:
#include <stdio.h>
#include <conio.h>
ARKADEEP DEY (CSE2015/030) CS392
189
#include <malloc.h>
typedef struct dnode{
int data;
dnode *rlink;
dnode *llink;
} dnode;
dnode *head;
void display(dnode*);
dnode* append(dnode*);
int count(dnode*);
int main()
{
int p,k;
dnode *d;
d=(dnode*)malloc(sizeof(dnode));
head=NULL;
d=head;
char c='Y';
while(c=='Y'||c=='y'){
d=append(d);
printf("Want to enter another node ?(Y/N) : ");
fflush(stdin);
scanf("%c",&c);
}
display(head);
ARKADEEP DEY (CSE2015/030) CS392
190
printf("\nThe no.of nodes = %d\n",count(head));
scanf("%d",&p);
return 0;
}
dnode* append(dnode *l){
char c;
dnode *node;
node=(dnode*)malloc(sizeof(dnode));
printf("\nEnter the data :");
scanf("%d",&node->data);
node->rlink=NULL;
if(head==NULL){
head=node;
l=head;
}
else{
l->rlink=node;
node->llink=l;
node->rlink=head;
head->llink=node;
l=node ;
}
return(l);
}
void display(dnode *h){
ARKADEEP DEY (CSE2015/030) CS392
191
do{
printf("[%u|%d|%u] -> ",h->llink,h->data,h->rlink);
h=h->rlink;
}while(h!=head);
printf("[%u|%d|%u] -> ",h->llink,h->data,h->rlink);
printf("\n----------------------------------------------\n");
}
int count(dnode *h){
int c=0;
do{
c++;
h=h->rlink;
}while(h!=head);
return c;
}
stAck-exPression evAluAtion
Q-58>Convert an infix exp. to postfix exp:
#include<stdio.h>
#include<string.h>
ARKADEEP DEY (CSE2015/030) CS392
192
#define size 10
char stack[size];
int tos=0,ele;
void push(int);
char pop();
void show();
int isempty();
int isfull();
char infix[30],output[30];
int prec(char);
int main()
{
int i=0,j=0,k=0,length;
char temp;
printf("\nEnter an infix expression:");
scanf("%s",infix);
printf("\nThe infix expresson is %s",infix);
length=strlen(infix);
for(i=0;i<length;i++)
{
//Numbers are added to the out put QUE
if(infix[i]!='+' && infix[i]!='-' && infix[i]!='*' && infix[i]!='/' && infix[i]!='^' && infix[i]!=')' && infix[i]!='(' )
{
output[j++]=infix[i];
ARKADEEP DEY (CSE2015/030) CS392
193
printf("\nThe element added to Q is:%c",infix[i]);
}
//If an operator or a bracket is encountered...
else
{
if(tos==0) //If there are no elements in the stack, the operator is added to it
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
}
else
{ //Operators or pushed or poped based on the order of precedence
if(infix[i]!=')' && infix[i]!='(')
{
if( prec(infix[i]) <= prec(stack[tos-1]) )
{
temp=pop();
printf("\n the poped element is :%c",temp);
output[j++]=temp;
push(infix[i]);
printf("\n The pushed element is :%c",infix[i]);
show();
}
else
ARKADEEP DEY (CSE2015/030) CS392
194
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
show();
}
}
else
{
if(infix[i]=='(')
{
push(infix[i]);
printf("\nThe pushed-- element is:%c",infix[i]);
}
if(infix[i]==')')
{
temp=pop();
while(temp!='(')
{output[j++]=temp;
printf("\nThe element added to Q is:%c",temp);
//temp=pop();
printf("\n the poped element is :%c",temp);
temp=pop();}
}
}
}
ARKADEEP DEY (CSE2015/030) CS392
195
}
printf("\nthe infix expression is: %s",output);
}
while(tos!=0)
{
output[j++]=pop();
}
printf("the infix expression is: %s\n",output);
getch();
}
//Functions for operations on stack
void push(int ele)
{
stack[tos]=ele;
tos++;
}
char pop()
{
tos--;
return(stack[tos]);
}
void show()
{
ARKADEEP DEY (CSE2015/030) CS392
196
int x=tos;
printf("--The Stack elements are.....");
while(x!=0)
printf("%c, ",stack[--x]);
}
int prec(char symbol)
{
if(symbol== '(')
return 0;
if(symbol== ')')
return 0;
if(symbol=='+' || symbol=='-')
return 1;
if(symbol=='*' || symbol=='/')
return 2;
if(symbol=='^')
return 3;
return 0;
}
ARKADEEP DEY (CSE2015/030) CS392
197
Q-59>Convert an infix exp. to prefix exp:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20
char stack[MAX];
int top = -1;
char pop();
void push(char item);
int prcd(char symbol) {
switch(symbol) {
case '+':
case '-':
return 2;
case '*':
ARKADEEP DEY (CSE2015/030) CS392
198
case '/':
return 4;
case '^':
case '$':
return 6;
case '(':
case ')':
case '#':
return 1;
}
}
int isoperator(char symbol) {
switch(symbol) {
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
default:
return 0;
}
ARKADEEP DEY (CSE2015/030) CS392
199
}
void convertip(char infix[],char prefix[]) {
int i,symbol,j=0;
char test[MAX];
infix=strrev(infix);
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
{
prefix[j]=symbol;
j++;
}else {
if(symbol==')')
{
push(symbol);
}else if(symbol=='(')
{
while(stack[top]!=')')
{
prefix[j]=pop();
j++;
}
pop();//pop ou
ARKADEEP DEY (CSE2015/030) CS392
200
}
else
{
if(prcd(symbol)>prcd(stack[top]))
{
push(symbol);
}else
{
while(prcd(symbol)<=prcd(stack[top]))
{
prefix[j]=pop();
j++;
}
push(symbol);
}//end of else.
}//end of else.
}//end of else.
}//end of for.
while(stack[top]!='#')
{
prefix[j]=pop();
j++;
}
prefix[j]='\0';//null terminate string.
prefix=strrev(prefix);
ARKADEEP DEY (CSE2015/030) CS392
201
}
int main()
{
char infix[20],prefix[20];
printf("Enter the valid infix string:\n");
gets(infix);
convertip(infix,prefix);
printf("The corresponding prefix string is:\n");
puts(prefix);
getch();
return 0;
}
void push(char item)
{
top++;
stack[top]=item;
}
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
ARKADEEP DEY (CSE2015/030) CS392
202
Queue
Q-60>.Program to Implement Priority Queue to Add and Delete Elements.
#include <stdio.h>
#include <stdlib.h> #define MAX 5 void insert_by_priority(int); void delete_by_priority(int); void create(); void check(int); void display_pqueue(); int pri_que[MAX]; int front, rear; int main(void) {
int n, ch; printf("\n1 - Insert an element into queue"); printf("\n2 - Delete an element from queue");
ARKADEEP DEY (CSE2015/030) CS392
203
printf("\n3 - Display queue elements"); printf("\n4 - Exit"); create(); while (1)
{ printf("\nEnter your choice : "); scanf("%d", &ch); switch (ch) { case 1: printf("\nEnter value to be inserted : "); scanf("%d",&n); insert_by_priority(n); break; case 2: printf("\nEnter value to delete : "); scanf("%d",&n); delete_by_priority(n); break; case 3: display_pqueue(); break; case 4: exit(0); default: printf("\nChoice is incorrect, Enter a correct choice");
}
}
} /* Function to create an empty priority queue */ void create() { front = rear = -1; } /* Function to insert value into priority queue */
ARKADEEP DEY (CSE2015/030) CS392
204
void insert_by_priority(int data) { if (rear >= MAX - 1) { printf("\nQueue overflow no more elements can be inserted"); return; } if ((front == -1) && (rear == -1)) { front++; rear++; pri_que[rear] = data; return; } else
check(data); rear++; } /* Function to check priority and place element */
void check(int data) {
int i,j; for (i = 0; i <= rear; ++){
if (data >= pri_que[i]) {
for (j = rear + 1; j > i;j--) {
pri_que[j] = pri_que[j - 1]; } pri_que[i] = data; return; } } pri_que[i] = data; } /* Function to delete an element from queue */
void delete_by_priority(int data) { int i; if ((front==-1) && (rear==-1)) {
printf("\nQueue is empty no elements to delete");
ARKADEEP DEY (CSE2015/030) CS392
205
return; } for (i = 0;i <= rear; i++) {
if (data == pri_que[i]) {
for (;i < rear; i++) {
pri_que[i] = pri_que[i + 1]; }
pri_que[i] = -99; rear--; if (rear == -1)
front = -1; return; } }
printf("\n%d not found in queue to delete", data); }
/* Function to display queue elements */
void display_pqueue() {
if ((front == -1) && (rear == -1)) {
printf("\nQueue is empty"); return; }
for (;front <= rear; front++) {
printf(" %d ", pri_que[front]); }
front = 0; }
ARKADEEP DEY (CSE2015/030) CS392
206
seArching-hAshing
Q-61>.Program to implement mid square hashing.
#include <stdio.h> #include <math.h> #include <stdlib.h> #include<unistd.h>
unsigned long long int randm(int n); unsigned long long int von(unsigned long long int x, int n);
int main(void)
{ unsigned long long int x, s; int n, i, r; printf("Enter the number of digits in the seed value "); scanf("%d", &n); printf("\nEnter the total number of random numbers to be generated "); scanf("%d", &r); if (n >= 12){ printf("TOO LARGE!!"); exit(0); } x = randm(n); for(i = 0; i < r; i++){
s = von(x, n);
ARKADEEP DEY (CSE2015/030) CS392
207
x = s; printf("\nRandom Number generated: %lld\n", s); }
return 0; }
/*Generating Random Number of desired digit*/
unsigned long long int randm(int n) {
double x; unsigned long long int y; srand(getpid());
x = rand() / (double)RAND_MAX; y = (unsigned long long int) (x * pow(10.0, n*1.0)); return y; }
/*Calculating Random Number By Von Neumann Middle Square method*/ unsigned long long int von(unsigned long long int x, int n)
{
unsigned long long int y;
int k;
k = n / 2;
y =(unsigned long long int)((x / pow(10.0, k * 1.0)) * x) % (unsigned long long int) (pow(10.0, n * 1.0));
return y;
} }
ARKADEEP DEY (CSE2015/030) CS392
208
Q-62>Program to implement modulo hash table.
#include <stdio.h> #include <math.h> #include <stdlib.h> #include<unistd.h>
unsigned long long int randm(int n);
unsigned long long int von(unsigned long long int x, int n); int main(void)
{
unsigned long long int x, s; int n, i, r; printf("Enter the number of digits in the seed value "); scanf("%d", &n); printf("\nEnter the total number of random numbers to be generated "); scanf("%d", &r); if (n >= 12){ printf("TOO LARGE!!"); exit(0); } x = randm(n); for(i = 0; i < r; i++){ s = von(x, n); x = s;
ARKADEEP DEY (CSE2015/030) CS392
209
printf("\nRandom Number generated: %lld\n", s); } return 0; } /*Generating Random Number of desired digit*/ unsigned long long int randm(int n) { double x; unsigned long long int y; srand(getpid());
x = rand() / (double)RAND_MAX;
y = (unsigned long long int) (x * pow(10.0, n*1.0)); return y; } /*Calculating Random Number By Von Neumann Middle Square method*/
unsigned long long int von(unsigned long long int x, int n)
{
unsigned long long int y; int k; k = n / 2; y =(unsigned long long int)((x / pow(10.0, k * 1.0)) * x) % (unsigned long long int) (pow(10.0, n * 1.0)); return y; } }
ARKADEEP DEY (CSE2015/030) CS392
210
Q-63>.Program to implement collision resolution technique hashing.
#include <stdio.h> #include <math.h> #include <stdlib.h> #include<unistd.h>
unsigned long long int randm(int n); unsigned long long int von(unsigned long long int x, int n);
int main(void)
{
unsigned long long int x, s;
int n, i, r; printf("Enter the number of digits in the seed value "); scanf("%d", &n); printf("\nEnter the total number of random numbers to be generated "); scanf("%d", &r); if (n >= 12){ printf("TOO LARGE!!"); exit(0);
ARKADEEP DEY (CSE2015/030) CS392
211
} x = randm(n); for(i = 0; i < r; i++){ s = von(x, n); x = s; printf("\nRandom Number generated: %lld\n", s); } return 0; } /*Generating Random Number of desired digit*/ unsigned long long int randm(int n) { double x; unsigned long long int y; srand(getpid());
x = rand() / (double)RAND_MAX;
y = (unsigned long long int) (x * pow(10.0, n*1.0)); return y; }
/*Calculating Random Number By Von Neumann Middle Square method*/ unsigned long long int von(unsigned long long int x, int n) { unsigned long long int y; int k; k = n / 2; y =(unsigned long long int)((x / pow(10.0, k * 1.0)) * x) % (unsigned long long int) (pow(10.0, n * 1.0)); return y; } }
ARKADEEP DEY (CSE2015/030) CS392
212
sorting
Q-64>efficient bubble sort:
#include<stdio.h> #include<conio.h>
void bblsrt(int,int[]);
void show(int,int[]);
int main()
{
int i,d[100],n,;
printf("\nEnter how many no:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter %d no:",i+1);
scanf("%d",&d[i]);
}
bblsrt(n,d);
getch();
ARKADEEP DEY (CSE2015/030) CS392
213
return 0;
}
void bblsrt(int n,int d[])
{
int i,j,t,flag;
for(i=0;i<n-1;i++)
{
flag=0;
for(j=0;j<n-i-1;j++)
{
if(d[j]>d[j+1])
{
flag=1;
t=d[j];
d[j]=d[j+1];
d[j+1]=t;
}
}
if(flag==0)
break;
printf("\nAfter %d iteration",i+1);
show(n,d);
}
}
void show(int n,int d[])
ARKADEEP DEY (CSE2015/030) CS392
214
{
int i;
printf("\nAfter sorted the array become:");
for(i=0;i<n;i++)
printf("\t%d",d[i]);
}
tree
Q-65>bst traverse(inorder,preorder,postorder)using function:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct bt
{
struct bt *lc;
int d;
ARKADEEP DEY (CSE2015/030) CS392
215
struct bt *rc;
};
void insert(struct bt **,int);
void inorder(struct bt *);
void preorder(struct bt *);
void postorder(struct bt *);
int n,i,num;
int main()
{
struct bt *bt;
bt='\0';
printf("Enter the number of items to be inserted: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the data: ");
scanf("%d",&num);
insert(&bt,num);
}
printf("\nIn-order Traversal: ");
inorder(bt);
printf("\nPre-order Traversal: ");
preorder(bt);
printf("\nPost-order Traversal:");
postorder(bt);
ARKADEEP DEY (CSE2015/030) CS392
216
getch();
}
void insert(struct bt **sr,int num)
{
if(*sr=='\0')
{
*sr=(struct bt *)malloc(sizeof(struct bt));
(*sr)->lc='\0';
(*sr)->d=num;
(*sr)->rc='\0';
}
else
{
if(num<(*sr)->d)
insert(&((*sr)->lc),num);
else
insert(&((*sr)->rc),num);
}
}
void inorder(struct bt *sr)
{
int i=0;
struct bt *n[100];
while(1)
{
ARKADEEP DEY (CSE2015/030) CS392
217
while(sr !='\0')
{
n[++i]=sr;
sr=sr->lc;
}
if(i != 0)
{
sr=n[i];
i--;
printf("%d ",sr->d);
sr=sr->rc;
}
else
break;
}
}
void preorder(struct bt *sr)
{
int i=0;
struct bt *n[100];
while(1)
{
while(sr !='\0')
{
printf("%d ",sr->d);
ARKADEEP DEY (CSE2015/030) CS392
218
n[++i]=sr;
sr=sr->lc;
}
if(i != 0)
{
sr=n[i];
i--;
sr=sr->rc;
}
else
break;
}
}
void postorder(struct bt *sr)
{
int i=0;
struct bt *n[100],*q='\0';
while(1)
{
while(sr !='\0')
{
n[++i]=sr;
sr=sr->lc;
}
if(i != 0)
ARKADEEP DEY (CSE2015/030) CS392
219
{
if(n[i]->rc!=q && n[i]->rc!='\0')
sr=n[i]->rc;
else
{
q=n[i--];
printf("%d ",q->d);
}
}
else
break;
}
}