DS

48
1 1. Write a program in “c “ language that accepts two matrices as input and print their product. Sol : #include<stdio.h> #include<conio.h> void input_mat(int x[10][10], int r, int c) { int i,j; printf("\nEnter the elements of the matrix:"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("Enter the element of [%d][%d] = ",i+1,j+1); fflush(stdin); scanf("%d",&x[i][j]); } } } void disp_mat(int x[10][10], int r, int c) { int i,j; for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d ", x[i][j]); } printf("\n"); } } int main() { int x[10][10],y[10][10],z[10][10],i,j,k,m,n,p,q; clrscr(); printf("\nEnter the row and column of the first matrix: "); scanf("%d%d",&m,&n); input_mat(x,m,n); printf("\nEnter the row and column of the second matrix: "); scanf("%d%d",&p,&q); input_mat(y,p,q);

Transcript of DS

Page 1: DS

1

1. Write a program in “c “ language that accepts two matrices as input and print their product.Sol :

#include<stdio.h>#include<conio.h>

void input_mat(int x[10][10], int r, int c){int i,j;printf("\nEnter the elements of the matrix:");for(i=0;i<r;i++){  for(j=0;j<c;j++)  {  printf("Enter the element of [%d][%d] = ",i+1,j+1);  fflush(stdin);  scanf("%d",&x[i][j]);  }}}

void disp_mat(int x[10][10], int r, int c){int i,j;for(i=0;i<r;i++){  for(j=0;j<c;j++)  {  printf("%d ", x[i][j]);  }  printf("\n");}

}

int main(){int x[10][10],y[10][10],z[10][10],i,j,k,m,n,p,q;

clrscr();

printf("\nEnter the row and column of the first matrix:  ");scanf("%d%d",&m,&n);

input_mat(x,m,n);

printf("\nEnter the row and column of the second matrix:  ");scanf("%d%d",&p,&q);input_mat(y,p,q);

printf("\The first matix is: \n");disp_mat(x,m,n);

printf("\The second matix is: \n");disp_mat(y,p,q);

for(i=0;i<m;i++){

Page 2: DS

2

  for(j=0;j<n;j++)  {  z[i][j]=0;  for(k=0;k<p;k++)  {    z[i][j]+=x[i][k]*y[k][j];  }  }}

printf("\nThe resultant matrix is: \n");disp_mat(z,m,p);

getch();return 0;}

2. Write a program in “c “ language to accept 10 strings as input and print them in lexicographic order.

Sol :#include<stdio.h>#include<conio.h>#include<string.h>

int strcomp(char *x, char *y){int a,i=0;while(x[i]!='\0'&&y[i]!='\0'){  if(x[i]==y[i])      a=0;  else  {  a=1;  break;  }  i++;}if(a==0){  if(x[i]=='\0'&&y[i]!='\0')      return 1;  if(x[i]!='\0'&&y[i]=='\0')      return 2;  return 0;}else{  if(x[i]>y[i])      return 2;  else      return 1;}

Page 3: DS

3

}

int main(){int i,j,k;char s[10][10],t[10];

clrscr();

printf("\nEnter 3 string: ");for(i=0;i<3;i++){  printf("\nEnter string %d : ",i+1);  gets(s[i]);}

printf("\nEnter 3 string are : \n");for(i=0;i<3;i++)  puts(s[i]);

for(i=0;i<3;i++){  for(j=i+1;j<3;j++)  {  k=strcomp(s[i],s[j]);  if(k==2)  {    t[0]='\0';    strcat(t,s[i]);    s[i][0]='\0';    strcat(s[i],s[j]);    s[j][0]='\0';    strcat(s[j],t);  }  }}

printf("\nAfter sorting the 3 string are : \n");for(i=0;i<3;i++)  puts(s[i]);

getch();return 0;}

3. Write a program in “c “ language that accepts two strings S1 and S2 input. The program should check of S2 is a sub string of S1 or not. If S2 is a sub string of S1, then the program should output the starting location and ending Location of S2 in S1. If S2 appears more than once in S1., then the locations of all instances have to be given.

Sol :

Page 4: DS

4

#include<stdio.h>#include<conio.h>#include<string.h>

int main(){char s1[100],s2[100];int i,j,k,f;

clrscr();

printf("\nEnter the first strig: ");gets(s1);printf("\nEnter the second strig: ");gets(s2);

for(i=0;s1[i]!='\0';i++){  f=0;  for(j=0,k=i;s2[j]!='\0';j++,k++)  {        if(s1[k]!=s2[j])        {      f++;      break;        }  }  if(f==0)  {    printf("\n\nThe second string(S2) presents in first string(S1) at location\n Strat=%d\nEnd=%d",i+1,i+j);  }}

printf("\nend");getch();return 0;

}

4. Write a program to concatenate two strings S1 and S2Sol :

#include<stdio.h>#include<conio.h>#include<string.h>

int main(){char s1[100],s2[100];int i,j,k,f;clrscr();printf("\nEnter the first strig: ");gets(s1);

Page 5: DS

5

printf("\nEnter the second strig: ");gets(s2);for(i=strlen(s1),j=0;s2[j]!='\0';i++,j++){  s1[i]=s2[j];}printf("\nAfter concatenation the first string becomes: %s",s1);getch();return 0;}

5. Write a program in “c” language to accept atwo singly linked lists A and B as input. Now, print a singly linked list that consists of only those elements, Which are common to both A and B

Sol :#include<stdio.h>#include<conio.h>#include<alloc.h>

struct node{int d;struct node *next;};struct node *create(){int i,n;struct node *f,*x,*l;printf("\nEnter no. of node to be created: ");scanf("%d",&n);x=(node *)malloc(sizeof(node));printf("\nEnter a no.  ");scanf("%d",&x->d);x->next=NULL;f=l=x;for(i=2;i<=n;i++){  x=(node *)malloc(sizeof(node));  printf("\nEnter a no.  ");  scanf("%d",&x->d);  x->next=NULL;  l->next=x;  l=x;}return f;}

void display(struct node *p){while(p!=NULL){  printf("%d ",p->d);  p=p->next;

Page 6: DS

6

}}void commonNode(struct node *x, struct node *y){int f=0;struct node *p,*q;p=x;printf("\nThe common node in the two lists are: ");while(p!=NULL){  q=y;  while(q!=NULL)  {   if(p->d==q->d)   {    f++;    printf("%d ",p->d);   }   q=q->next;  }  p=p->next;}if(f==0)     printf("\n\n\tNo common node in the list A and B");

}

int main(){

clrscr();struct node *a,*b;a=create();b=create();printf("\nThe first linked list is: ");display(a);printf("\nThe second linked list is: ");display(B);commonNode(a,B);getch();return 0;}

6. Write a program in “c” language to accept a singly linked list of integers as input. Now, sort the elements of the list in ascending order. Then, accept an integer as input. Insert this integer into the singly linked list at the appropriate position.

Sol :#include<stdio.h>#include<conio.h>#include<alloc.h>

struct node{int d;

Page 7: DS

7

struct node *next;};

struct node *create(){int i,n;struct node *f,*x,*l;printf("\nEnter no. of node to be created: ");scanf("%d",&n);x=(node *)malloc(sizeof(node));printf("\nEnter a no.  ");scanf("%d",&x->d);x->next=NULL;f=l=x;for(i=2;i<=n;i++){  x=(node *)malloc(sizeof(node));  printf("\nEnter a no.  ");  scanf("%d",&x->d);  x->next=NULL;  l->next=x;  l=x;}return f;}

void display(struct node *p){while(p!=NULL){  printf("%d ",p->d);  p=p->next;}}

struct node *sortList(struct node *x){int t;struct node *p,*q;p=x;for(;x!=NULL;x=x->next){      for(q=x->next;q!=NULL;q=q->next)      {  if(x->d>q->d)  {   t=x->d;   x->d=q->d;   q->d=t;  }      }}return p;}

Page 8: DS

8

int main(){

int f=0;struct node *a,*x,*p,*b;

clrscr();a=create();printf("\nThe first linked list is: ");display(a);

a=sortList(a);

printf("\nAfter sorting the linked list is: ");display(a);

x=(node *)malloc(sizeof(node));printf("\nEnter a number to be inserted im the linked list: ");scanf("%d",&x->d);x->next=NULL;

p=a;if(p->next==NULL)     if(p->d<x->d)  p->next=x;     else     {  x->next=p;  a=x;     }else{     if(p->d>x->d)     {  x->next=p;  a=x;     }     else     {  b=a->next;  while(b!=NULL)  {   if((p->d < x->d) && (b->d > x->d))   {       x->next=b;       p->next=x;       f++;       break;   }   p=b;   b=b->next;  }  if(f==0)

Page 9: DS

9

  {    p->next=x;  }     }}

printf("\nAfter insertion the linked list is: ");display(a);

getch();return 0;}

7. Write a program in “c” language to converts prefix expression to a postfix expression using pointers.

Sol :#include<stdio.h>#include<conio.h>#include<alloc.h>

struct node{int d;struct node *next;};

struct node *create(){int i,n;struct node *f,*x,*l;printf("\nEnter no. of node to be created: ");scanf("%d",&n);x=(node *)malloc(sizeof(node));printf("\nEnter a no.  ");scanf("%d",&x->d);x->next=NULL;f=l=x;for(i=2;i<=n;i++){  x=(node *)malloc(sizeof(node));  printf("\nEnter a no.  ");  scanf("%d",&x->d);  x->next=NULL;  l->next=x;  l=x;}return f;}

void display(struct node *p){while(p!=NULL){  printf("%d ",p->d);

Page 10: DS

10

  p=p->next;}}

struct node *sortList(struct node *x){int t;struct node *p,*q;p=x;for(;x!=NULL;x=x->next){      for(q=x->next;q!=NULL;q=q->next)      {  if(x->d>q->d)  {  t=x->d;  x->d=q->d;  q->d=t;  }      }}return p;}

int main(){

int f=0;struct node *a,*x,*p,*b;

clrscr();a=create();printf("\nThe first linked list is: ");display(a);

a=sortList(a);

printf("\nAfter sorting the linked list is: ");display(a);

x=(node *)malloc(sizeof(node));printf("\nEnter a number to be inserted im the linked list: ");scanf("%d",&x->d);x->next=NULL;

p=a;if(p->next==NULL)    if(p->d<x->d)  p->next=x;    else    {  x->next=p;  a=x;    }

Page 11: DS

11

else{    if(p->d>x->d)    {  x->next=p;  a=x;    }    else    {  b=a->next;  while(b!=NULL)  {  if((p->d < x->d) && (b->d > x->d))  {      x->next=b;      p->next=x;      f++;      break;  }  p=b;  b=b->next;  }  if(f==0)  {    p->next=x;  }    }}

printf("\nAfter insertion the linked list is: ");display(a);

getch();return 0;}

8. Write a program in “c” language to reverse an input string.Sol :

#include<stdio.h>#include<conio.h>#include<string.h>

void rev_rec(char *str, int start, int end){char t;if(end-start<=0)  return;t=str[start];str[start]=str[end];str[end]=t;rev_rec(str, start+1, end-1);}

Page 12: DS

12

int main(){char *s;int len;

clrscr();

printf("\nEnter a string: ");gets(s);

len=strlen(s);

printf("\nEntered string is: %s",s);rev_rec(s,0,len-1);printf("\nAfter reverse the string is: %s",s);

getch();return 0;}

9. Write a program in “c” language to implement a Dequeue using pointers. All operations associate with a Dequeue are to be implemented.

Sol :#include<stdio.h>#include<conio.h>#include<alloc.h>#include<STDLIB.h>

struct node{int d;struct node *next;};

struct node *createQ(){int i,n;struct node *f=NULL,*x,*r=NULL;printf("\nEnter no. of node to be created in the queue: ");scanf("%d",&n);

for(i=1;i<=n;i++){  x=(node *)malloc(sizeof(node));  printf("Enter a no.  ");  scanf("%d",&x->d);  x->next=NULL;  if(f==NULL)    f=r=x;  else  {    r->next=x;    r=x;  }

Page 13: DS

13

}return f;}

void display(struct node *p){while(p!=NULL){  printf("%d ",p->d);  p=p->next;}}

struct node *ReverseQ(struct node *x){int t;struct node *p,*q,*start=NULL;p=x;while(p!=NULL){  q=(node *)malloc(sizeof(node));  q->next=NULL;  q->d=p->d;  if(x->next==NULL)  {  start=q;  }  else  {  q->next=start;  start=q;  }  p=p->next;}

return start;}

struct node *ins_f(struct node *a){struct node *x;

x=(node *)malloc(sizeof(node));printf("Enter a no.  ");scanf("%d",&x->d);x->next=a;a=x;return a;}

struct node *ins_r(struct node *a){struct node *x,*p;

Page 14: DS

14

x=(node *)malloc(sizeof(node));printf("Enter a no.  ");scanf("%d",&x->d);x->next=NULL;if(a==NULL){  a=x;  return a;}p=a;while(p->next!=NULL)  p=p->next;

p->next=x;return a;}struct node *del_r(struct node *a){int item;struct node *x,*p;

if(a==NULL){        printf("Underflow");        getch();        return a;}else if(a->next==NULL)      {  item=a->d;  a=NULL;      }      else      {  p=a;  while((p->next)->next!=NULL)  p=p->next;

  p->next=NULL;  item=(p->next)->d;  //free((p->next)->d);      }

printf("%d is deleted from the rear end oif the queue",item);getch();return a;}

struct node *del_f(struct node *a){int item;struct node *x,*p;

Page 15: DS

15

if(a==NULL){        printf("Underflow");        getch();        return a;}else if(a->next==NULL)      {  item=a->d;  a=NULL;      }      else      {  p=a;  a=a->next;  p->next=NULL;  item=p->d;      }printf("%d is deleted from the rear end oif the queue",item);getch();return a;}

int main(){struct node *a,*rev,*x;int ch;

clrscr();

a=createQ();

while(1){  clrscr();;  gotoxy(35,3);  printf("MENU");  gotoxy(25,5);  printf("1. Insertion");  gotoxy(25,6);  printf("2. Deletion");  gotoxy(25,7);  printf("3. Display");  gotoxy(25,8);  printf("4. Exit");  gotoxy(20,15);  printf("Enetr your choice(1-4):  ");  scanf("%d",&ch);  switch(ch)  {  case 1:    do    {    clrscr();

Page 16: DS

16

    gotoxy(35,3);    printf("INSERTION MENU");    gotoxy(25,5);    printf("1. Insertion at front");    gotoxy(25,6);    printf("2. Insertion at rear");    gotoxy(25,7);    printf("3. Retrun to main menu");    gotoxy(20,15);    printf("Enetr your choice(1-3):  ");    scanf("%d",&ch);    switch(ch)    {      case 1: a=ins_f(a);      break;      case 2: a=ins_r(a);      break;      case 3: break;      default: printf("\nWrong choice. Try again");    }    }while(ch!=3);    break;  case 2:    do    {    clrscr();    gotoxy(35,3);    printf("DELETION MENU");    gotoxy(25,5);    printf("1. deletion at front");    gotoxy(25,6);    printf("2. Deletion at rear");    gotoxy(25,7);    printf("3. Retrun to main menu");    gotoxy(20,15);    printf("Enetr your choice(1-3):  ");    scanf("%d",&ch);    switch(ch)    {      case 1: a=del_f(a);      break;      case 2: a=del_r(a);      //if(a==NULL)

      break;      case 3: break;      default: printf("\nWrong choice. Try again");    }    }while(ch!=3);    break;

  case 3: clrscr();    gotoxy(10,15);    printf("The queue elements are: ");

Page 17: DS

17

    display(a); getch();    break;

  case 4:    exit(0);  }}

return 0;}

10. Write a program in “c” language to reverse the elements of a queue.Sol :

#include<stdio.h>#include<conio.h>#include<alloc.h>

struct node{int d;struct node *next;};

struct node *create(){int i,n;struct node *f,*x,*r;printf("\nEnter no. of node to be created in the queue: ");scanf("%d",&n);x=(node *)malloc(sizeof(node));printf("\nEnter a no.  ");scanf("%d",&x->d);x->next=NULL;f=r=x;for(i=2;i<=n;i++){  x=(node *)malloc(sizeof(node));  printf("Enter a no.  ");  scanf("%d",&x->d);  x->next=NULL;  r->next=x;  r=x;}return f;}

void display(struct node *p){while(p!=NULL){  printf("%d ",p->d);  p=p->next;}}

Page 18: DS

18

struct node *ReverseQ(struct node *x){int t;struct node *p,*q,*start=NULL;p=x;while(p!=NULL){  q=(node *)malloc(sizeof(node));  q->next=NULL;  q->d=p->d;  if(x->next==NULL)  {  start=q;  }  else  {  q->next=start;  start=q;  }  p=p->next;}

return start;}

int main(){struct node *a,*rev;

clrscr();a=create();printf("\nThe element of the queue is: ");display(a);

rev=ReverseQ(a);

printf("\nReverse queue is: ");display(rev);

getch();return 0;}

11. Write a program in “c” language to implement a queue using two stacks.Sol :

#include<stdio.h>#include<conio.h>#include<stdlib.h>

struct node{int d;struct node *next;

Page 19: DS

19

};

struct node *createQ(struct){struct node *t1=NULL,*t2=NULL,*x;

x=(node *)malloc(sizeof(node));printf("Enter a no.  ");scanf("%d",&x->d);x->next=NULL;

if(f==NULL)    f=r=x;  else  {    r->next=x;    r=x;  }}return f;}

void display(struct node *p){while(p!=NULL){  printf("%d ",p->d);  p=p->next;}}

int main(){int ch;struct node *r,*f;r=f=NULL;

clrscr();

while(1){  printf("\n\n\t\tMENU");  printf("\n\n\t1. Insert");  printf("\n\t2. Delete");  printf("\n\t3. Display");  printf("\n\t4. Exit");  printf("\n\nEnter your choice(1-4): ");  fflush(stdin);  scanf("%d",&ch);  switch(ch)  {  case 1: insert(

Page 20: DS

20

    break;  case 2:    break;  case 3:    break;  case 4: exit(0);    break;  default: printf("\n\nWrong input. Try again!!!");  }}getch();return 0;}

12. Write a program in “c” language for the creation of a binary tree. Also, provide for insertion and deletion operations.

Sol :#include<stdio.h>#include<conio.h>#include<alloc.h>#include<stdlib.h>#include<ctype.h>

struct node{int d;struct node *l,*r;};

void inorder(struct node *root){if(root!=NULL){  inorder(root->l);  printf("%d ",root->d);  inorder(root->r);}}

void preorder(struct node *root){if(root!=NULL){  printf("%d ",root->d);  preorder(root->l);  preorder(root->r);}}

void postorder(struct node *root){if(root!=NULL){  postorder(root->l);

Page 21: DS

21

  postorder(root->r);  printf("%d ",root->d);}}

int main(){struct node *root=NULL,*p,*q;char ch='y';

clrscr();

while(tolower(ch)=='y'){

  p=(struct node *)malloc(sizeof(node));  if(p==NULL)  {  printf("\nTry Again!!!!");  break;  }  printf("\nEnter the element: ");  scanf("%d",&p->d);  p->l=p->r=NULL;  if(root==NULL)  {    root=p;  }  else  {    q=root;    while(1)    {    if(p->d<q->d)    {      if(q->l==NULL)      {      q->l=p;      break;      }      else          q=q->l;    }    else    {      if(q->r==NULL)      {      q->r=p;      break;      }      else          q=q->r;

Page 22: DS

22

    }    }  }  printf("\nDo u want to continue(y/n):  ");  fflush(stdin);  scanf("%c",&ch);}

printf("\nInorder is : ");inorder(root);

printf("\nPreorder is : ");preorder(root);

printf("\nPostorder is : ");postorder(root);

getch();return 0;}

13. Write a program in “c” language for pre-order, post-order and in-ordertraversals of a Binary tree. Don’t use Recursion.

Sol : #include<stdio.h>#include<conio.h>#include<alloc.h>#include<stdlib.h>#include<ctype.h>

struct node{int d;struct node *l,*r;};

//Inorder, Preorder, Postorder funtions without using recursionstruct node *stack[100];int sp=0;

void push(struct node *root){if(sp==100){  printf("overflow");}else{  stack[sp]=root;  sp++;}}

Page 23: DS

23

struct node *pop(){if(sp==0){  return NULL;}--sp;return stack[sp];}

void inorder(struct node *root){while(1){  if(root!=NULL)  {  push(root);  printf("\ncheck=%d",root->d);  root=root->l;  }  else  {  if( (root==pop())==NULL)      return;  else  {    printf("%d ",root->d);    root=root->r;  }  }}}

/*void preorder(struct node *root){if(root!=NULL){  printf("%d ",root->d);  preorder(root->l);  preorder(root->r);}}

void postorder(struct node *root){if(root!=NULL){  postorder(root->l);  postorder(root->r);  printf("%d ",root->d);}} */

Page 24: DS

24

int main(){struct node *root=NULL,*p,*q;char ch='y';

clrscr();

while(tolower(ch)=='y'){

  p=(struct node *)malloc(sizeof(node));  if(p==NULL)  {  printf("\nTry Again!!!!");  break;  }  printf("\nEnter the element: ");  scanf("%d",&p->d);  p->l=p->r=NULL;  if(root==NULL)  {    root=p;  }  else  {    q=root;    while(1)    {    if(p->d<q->d)    {      if(q->l==NULL)      {      q->l=p;      break;      }      else          q=q->l;    }    else    {      if(q->r==NULL)      {      q->r=p;      break;      }      else          q=q->r;    }    }  }  printf("\nDo u want to continue(y/n):  ");  fflush(stdin);  scanf("%c",&ch);

Page 25: DS

25

}

printf("\nInorder is : ");inorder(root);

/*printf("\nPreorder is : ");preorder(root);

printf("\nPostorder is : ");postorder(root);*/

getch();return 0;}

14. Write a program in “c” language to accept a tree as input and converts it into binary tree. Print the resultant binary tree.

Sol : #include<stdio.h>#include<conio.h>

struct tree{int d;struct tree *l;struct tree *r;};

int count_node(struct tree *h){if(h==NULL){  printf("\nTree is empty");  getch();  return 0;}if(h->l!=NULL || h->r!=NULL){  c++;  return c;}if(h->l!=NULL)    count_node(h->l);if(h->r!=NULL)    count_node(h->r);}

struct tree *ins_tree(struct tree *h, int n){struct tree *x;x=(struct tree*)malloc(size(struct tree));x->l=NULL;

Page 26: DS

26

x->r=NULL;if(h==NULL)    return x;if(n<=h->d)    h->l=ins_tree(h->l,n)else    h->r=ins_tree(h->r,n);return h;

}

int main(){clrscr();

getch();return 0;}

15. Write a program in “c “ language to inserts 15,25,2,4,3,1,50 into an initially empty AVL tree. Make assumptions, If necessary.

Sol : #include <stdio.h>#include <conio.h>#include <malloc.h>

#define FALSE 0#define TRUE 1

struct AVLNode{int data ;int balfact ;struct AVLNode *left ;struct AVLNode *right ;} ;

struct AVLNode * buildtree ( struct AVLNode *, int, int * ) ;struct AVLNode * deldata ( struct AVLNode *, int, int * ) ;struct AVLNode * del ( struct AVLNode *, struct AVLNode *, int * ) ;struct AVLNode * balright ( struct AVLNode *, int * ) ;struct AVLNode * balleft ( struct AVLNode *, int * ) ;void display ( struct AVLNode * ) ;void deltree ( struct AVLNode * ) ;

void main( ){struct AVLNode *avl = NULL ;int h ;

Page 27: DS

27

avl = buildtree ( avl, 15, &h ) ;avl = buildtree ( avl, 25, &h ) ;avl = buildtree ( avl, 2, &h ) ;avl = buildtree ( avl, 4, &h ) ;avl = buildtree ( avl, 3, &h ) ;avl = buildtree ( avl, 1, &h ) ;avl = buildtree ( avl, 50, &h ) ;

printf ( "\nAVL tree:\n" ) ;display ( avl ) ;

avl = deldata ( avl, 20, &h ) ;avl = deldata ( avl, 12, &h ) ;

printf ( "\nAVL tree after deletion of a node:\n" ) ;display ( avl ) ;

deltree ( avl ) ;

getch( ) ;}

/* inserts an element into tree */struct AVLNode * buildtree ( struct AVLNode *root, int data, int *h ){struct AVLNode *node1, *node2 ;

if ( !root ){  root = ( struct AVLNode * ) malloc ( sizeof ( struct AVLNode ) ) ;  root -> data = data ;  root -> left = NULL ;  root -> right = NULL ;  root -> balfact = 0 ;  *h = TRUE ;  return ( root ) ;}

if ( data < root -> data ){  root -> left = buildtree ( root -> left, data, h ) ;  /* If left subtree is higher */  if ( *h )  {   switch ( root -> balfact )   {    case 1:     node1 = root -> left ;     if ( node1 -> balfact == 1 )     {      printf ( "\nRight rotation along %d.", root -> data ) ;      root -> left = node1 -> right ;      node1 -> right = root ;      root -> balfact = 0 ;

Page 28: DS

28

      root = node1 ;     }     else     {      printf ( "\nDouble rotation, left along %d",                                                            node1 -> data ) ;      node2 = node1 -> right ;      node1 -> right = node2 -> left ;      printf ( " then right along %d.\n", root -> data ) ;      node2 -> left = node1 ;      root -> left = node2 -> right ;      node2 -> right = root ;      if ( node2 -> balfact == 1 )       root -> balfact = -1 ;      else       root -> balfact = 0 ;      if ( node2 -> balfact == -1 )       node1 -> balfact = 1 ;      else       node1 -> balfact = 0 ;      root = node2 ;     }     root -> balfact = 0 ;     *h = FALSE ;     break ;

    case 0:     root -> balfact = 1 ;     break ;

    case -1:     root -> balfact = 0 ;     *h = FALSE ;   }  }}

if ( data > root -> data ){  root -> right = buildtree ( root -> right, data, h ) ;  /* If the right subtree is higher */  if ( *h )  {   switch ( root -> balfact )   {    case 1:     root -> balfact = 0 ;     *h = FALSE ;     break ;

    case 0:     root -> balfact = -1 ;     break;

Page 29: DS

29

    case -1:     node1 = root -> right ;     if ( node1 -> balfact == -1 )     {      printf ( "\nLeft rotation along %d.", root -> data ) ;      root -> right = node1 -> left ;      node1 -> left = root ;      root -> balfact = 0 ;      root = node1 ;     }     else     {      printf ( "\nDouble rotation, right along %d",                                                            node1 -> data ) ;      node2 = node1 -> left ;      node1 -> left = node2 -> right ;      node2 -> right = node1 ;      printf ( " then left along %d.\n", root -> data ) ;      root -> right = node2 -> left ;      node2 -> left = root ;

      if ( node2 -> balfact == -1 )       root -> balfact = 1 ;      else       root -> balfact = 0 ;      if ( node2 -> balfact == 1 )       node1 -> balfact = -1 ;      else       node1 -> balfact = 0 ;      root = node2 ;     }     root -> balfact = 0 ;     *h = FALSE ;   }  }}return ( root ) ;}

/* deletes an item from the tree */struct AVLNode * deldata ( struct AVLNode *root, int data, int *h ){struct AVLNode *node ;

if ( !root ){  printf ( "\nNo such data." ) ;  return ( root ) ;}else{  if ( data < root -> data )  {   root -> left = deldata ( root -> left, data, h ) ;

Page 30: DS

30

   if ( *h )    root = balright ( root, h ) ;  }  else  {   if ( data > root -> data )   {    root -> right = deldata ( root -> right, data, h ) ;    if ( *h )     root = balleft ( root, h ) ;   }   else   {    node = root ;    if ( node -> right == NULL )    {     root = node -> left ;     *h = TRUE ;     free ( node ) ;    }    else    {     if ( node -> left == NULL )     {      root = node -> right ;      *h = TRUE ;      free ( node ) ;     }     else     {      node -> right = del ( node -> right, node, h ) ;      if ( *h )       root = balleft ( root, h ) ;     }    }   }  }}return ( root ) ;}

struct AVLNode * del ( struct AVLNode *succ, struct AVLNode *node, int *h ){struct AVLNode *temp = succ ;if ( succ -> left != NULL ){  succ -> left = del ( succ -> left, node, h ) ;  if ( *h )   succ = balright ( succ, h ) ;}else{  temp = succ ;  node -> data = succ -> data ;

Page 31: DS

31

  succ = succ -> right ;  free ( temp ) ;  *h = TRUE ;}return ( succ ) ;}

/* balances the tree, if right sub-tree is higher */struct AVLNode * balright ( struct AVLNode *root, int *h ){struct AVLNode *node1, *node2 ;

switch ( root -> balfact ){  case 1:   root -> balfact = 0 ;   break;

  case 0:   root -> balfact = -1 ;   *h  = FALSE ;   break;

  case -1:   node1 = root -> right ;   if ( node1 -> balfact <= 0 )   {    printf ( "\nLeft rotation along %d.", root -> data ) ;    root -> right = node1 -> left ;    node1 -> left = root ;    if ( node1 -> balfact == 0 )    {     root -> balfact = -1 ;     node1 -> balfact = 1 ;       *h = FALSE ;    }    else    {     root -> balfact = node1 -> balfact = 0 ;    }    root = node1 ;   }   else   {    printf ( "\nDouble rotation, right along %d", node1 -> data );    node2 = node1 -> left ;    node1 -> left = node2 -> right ;    node2 -> right = node1 ;    printf ( " then left along %d.\n", root -> data );    root -> right = node2 -> left ;    node2 -> left = root ;

    if ( node2 -> balfact == -1 )     root -> balfact = 1 ;

Page 32: DS

32

    else     root -> balfact = 0 ;    if ( node2 -> balfact == 1 )     node1 -> balfact = -1 ;    else     node1 -> balfact = 0 ;    root = node2 ;    node2 -> balfact = 0 ;   }}return ( root ) ;}

/* balances the tree, if left sub-tree is higher */struct AVLNode * balleft ( struct AVLNode *root, int *h ){struct AVLNode *node1, *node2 ;

switch ( root -> balfact ){  case -1:   root -> balfact = 0 ;   break ;

  case 0:   root -> balfact = 1 ;   *h = FALSE ;   break ;

  case 1:   node1 = root -> left ;   if ( node1 -> balfact >= 0 )   {    printf ( "\nRight rotation along %d.", root -> data ) ;    root -> left = node1 -> right ;    node1 -> right = root ;    if ( node1 -> balfact == 0 )    {     root -> balfact = 1 ;     node1 -> balfact = -1 ;     *h = FALSE ;    }    else    {     root -> balfact = node1 -> balfact = 0 ;    }    root = node1 ;   }   else   {    printf ( "\nDouble rotation, left along %d", node1 -> data ) ;    node2 = node1 -> right ;    node1 -> right = node2 -> left ;    node2 -> left = node1 ;

Page 33: DS

33

    printf ( " then right along %d.\n", root -> data ) ;    root -> left = node2 -> right ;    node2 -> right = root ;

    if ( node2 -> balfact == 1 )     root -> balfact = -1 ;    else     root -> balfact = 0 ;    if ( node2-> balfact == -1 )     node1 -> balfact = 1 ;    else     node1 -> balfact = 0 ;    root = node2 ;    node2 -> balfact = 0 ;   }}return ( root ) ;}

/* displays the tree in-order */void display ( struct AVLNode *root ){if ( root != NULL ){  display ( root -> left ) ;  printf ( "%d\t", root -> data ) ;  display ( root -> right ) ;}}

/* deletes the tree */void deltree ( struct AVLNode *root ){if ( root != NULL ){  deltree ( root -> left ) ;  deltree ( root -> right ) ;}free ( root ) ;}

16. Write a program in “c” language to implement Dijstara’s algorithm.Sol :

void DIJKSTRA(){  int A[N][N], i, u, v, s, c, N, MAXD;  int PQ[N], dist[N], Adj[N];  for(v = 0; v < N; v++){    if(v = s)      dist[v] = 0;    else      dist[v] = MAXD;    PQ[v] = dist[v];  }  i = N-1;

Page 34: DS

34

  while(i > 0){    for(j = 0; j < i; j++)      if(PQ[j] < PQ[i])        swap(PQ[j], PQ[i]);    u = PQ[i];    for(v = 0; v < N, A[u][v] != 0; j++){      c = dist[u] + A[u][v];      if(c < dist[v])        dist[v] = c;    }    i = i-1;  }}

17. Write a program to implement QUICK Sort.Sol :

#define maxsize 6int A[maxsize];

void quicksort(int a, int B){  int rtidx=0,ltidx=0,k=a,l=0,pivot;  int leftarr[maxsize],rtarr[maxsize];  pivot=A[a];  if(a==b)return;  while(k<b)  {    ++k;  if(A[k]<A[a])  {   leftarr[ltidx]=A[k];   ltidx++;   }  else  {  rtarr[rtidx]=A[k];  rtidx++;   }    }

  k=a;  for(l=0;l<ltidx;++l)A[k++]=leftarr[l];  A[k++]=pivot;  for(l=0;l<rtidx;++l)A[k++]=rtarr[l];  if(ltidx>0)quicksort(a,a+ltidx-1);  if(rtidx>0)quicksort(b-rtidx+1,B);  }

void printarr(int a){  int i;  for(i=0;i<a;i++)  {  printf("%d",A[i]);  printf("\n");

Page 35: DS

35

  }  }

main(){  int i,s;  printf("enter the number of numbers to be entered \n");  scanf("%d",&s);  for(i=0;i<s;i++)  {  printf("enter the number \n" );  scanf("%d",&A[i]);  }  printf("array before sorting ");  printarr(s);  quicksort(0,s-1);  printf("array after sorting");  printarr(s);  }

Page 36: DS

36

18. Write a program in “c “ language to insert 15,25,2, 4, 3, 1, and 50 into an initially empty Splay tree.

Sol :/*splay.h*/

        #include <stdlib.h>        #include "fatal.h"

        typedef int ElementType;        #define Infinity 30000        #define NegInfinity (-30000)

/* START*/        #ifndef _Splay_H        #define _Splay_H

        struct SplayNode;        typedef struct SplayNode *SplayTree;

        SplayTree MakeEmpty( SplayTree T );        SplayTree Find( ElementType X, SplayTree T );        SplayTree FindMin( SplayTree T );        SplayTree FindMax( SplayTree T );        SplayTree Initialize( void );        SplayTree Insert( ElementType X, SplayTree T );        SplayTree Remove( ElementType X, SplayTree T );        ElementType Retrieve( SplayTree T );  /* Gets root item */

        #endif  /* _Splay_H *//* END */

/*fatal.h*/#include <stdio.h>#include <stdlib.h>

#define Error( Str )        FatalError( Str )#define FatalError( Str )   fprintf( stderr, "%s\n", Str ), exit( 1 )

splay.c

#include "splay.h"        #include <stdlib.h>        #include "fatal.h"                struct SplayNode        {            ElementType Element;            SplayTree      Left;            SplayTree      Right;        };

        typedef struct SplayNode *Position;        static Position NullNode = NULL;  /* Needs initialization */

Page 37: DS

37

        SplayTree        Initialize( void )        {            if( NullNode == NULL )            {                NullNode = malloc( sizeof( struct SplayNode ) );                if( NullNode == NULL )                    FatalError( "Out of space!!!" );                NullNode->Left = NullNode->Right = NullNode;            }            return NullNode;        }

        static SplayTree Splay( ElementType Item, Position X );

        SplayTree        MakeEmpty( SplayTree T )        {            if( T != NullNode )            {                MakeEmpty( T->Left );                MakeEmpty( T->Right );                free( T );            }            return NullNode;        }

        void        PrintTree( SplayTree T )        {            if( T != NullNode )            {                PrintTree( T->Left );                printf( "%d ", T->Element );                PrintTree( T->Right );            }        }

        SplayTree        Find( ElementType X, SplayTree T )        {            return Splay( X, T );        }

        SplayTree        FindMin( SplayTree T )        {            return Splay( NegInfinity, T );        }

        SplayTree        FindMax( SplayTree T )        {

Page 38: DS

38

            return Splay( Infinity, T );        }

        /* This function can be called only if K2 has a left child */        /* Perform a rotate between a node (K2) and its left child */        /* Update heights, then return new root */

        static Position        SingleRotateWithLeft( Position K2 )        {            Position K1;

            K1 = K2->Left;            K2->Left = K1->Right;            K1->Right = K2;

            return K1;  /* New root */        }

        /* This function can be called only if K1 has a right child */        /* Perform a rotate between a node (K1) and its right child */        /* Update heights, then return new root */

        static Position        SingleRotateWithRight( Position K1 )        {            Position K2;

            K2 = K1->Right;            K1->Right = K2->Left;            K2->Left = K1;

            return K2;  /* New root */        }

/* START: fig12_6.txt */        /* Top-down splay procedure, */        /* not requiring Item to be in tree */

        SplayTree        Splay( ElementType Item, Position X )        {            static struct SplayNode Header;            Position LeftTreeMax, RightTreeMin;

            Header.Left = Header.Right = NullNode;            LeftTreeMax = RightTreeMin = &Header;            NullNode->Element = Item;

            while( Item != X->Element )            {                if( Item < X->Element )                {                    if( Item < X->Left->Element )

Page 39: DS

39

                        X = SingleRotateWithLeft( X );                    if( X->Left == NullNode )                        break;                    /* Link right */                    RightTreeMin->Left = X;                    RightTreeMin = X;                    X = X->Left;                }                else                {                    if( Item > X->Right->Element )                        X = SingleRotateWithRight( X );                    if( X->Right == NullNode )                        break;                    /* Link left */                    LeftTreeMax->Right = X;                    LeftTreeMax = X;                    X = X->Right;                }            }  /* while Item != X->Element */

            /* Reassemble */            LeftTreeMax->Right = X->Left;            RightTreeMin->Left = X->Right;            X->Left = Header.Right;            X->Right = Header.Left;

            return X;        }/* END */

/* START: fig12_7.txt */        SplayTree        Insert( ElementType Item, SplayTree T )        {            static Position NewNode = NULL;

            if( NewNode == NULL )            {                NewNode = malloc( sizeof( struct SplayNode ) );                if( NewNode == NULL )                    FatalError( "Out of space!!!" );            }            NewNode->Element = Item;

            if( T == NullNode )            {                NewNode->Left = NewNode->Right = NullNode;                T = NewNode;            }            else            {                T = Splay( Item, T );                if( Item < T->Element )

Page 40: DS

40

                {                    NewNode->Left = T->Left;                    NewNode->Right = T;                    T->Left = NullNode;                    T = NewNode;                }                else                if( T->Element < Item )                {                    NewNode->Right = T->Right;                    NewNode->Left = T;                    T->Right = NullNode;                    T = NewNode;                }                else                    return T;  /* Already in the tree */            }

            NewNode = NULL;   /* So next insert will call malloc */            return T;        }/* END */

/* START */        SplayTree        Remove( ElementType Item, SplayTree T )        {            Position NewTree;

            if( T != NullNode )            {                T = Splay( Item, T );                if( Item == T->Element )                {                    /* Found it! */                    if( T->Left == NullNode )                        NewTree = T->Right;                    else                    {                        NewTree = T->Left;                        NewTree = Splay( Item, NewTree );                        NewTree->Right = T->Right;                    }                    free( T );                    T = NewTree;                }            }

            return T;        }

/* END */

        ElementType

Page 41: DS

41

        Retrieve( SplayTree T )        {            return T->Element;        }

main prog

#include "splay.h"#include <stdio.h>#define NumItems 500

main( ){    SplayTree T;    SplayTree P;    int i;    int j = 0;

    T = Initialize( );    T = MakeEmpty( T );    for( i = 0; i < NumItems; i++, j = ( j + 7 ) % NumItems )        T = Insert( j, T );      for( j = 0; j < 2; j++ )        for( i = 0; i < NumItems; i++ )        {            T = Find( i, T );            if( Retrieve( T ) != i )                printf( "Error1 at %d\n", i );        }

    printf( "Entering remove\n" );

    for( i = 0; i < NumItems; i += 2 )        T = Remove( i, T );

    for( i = 1; i < NumItems; i += 2 )    {        T = Find( i, T );        if( Retrieve( T ) != i )            printf( "Error2 at %d\n", i );    }

    for( i = 0; i < NumItems; i += 2 )    {        T = Find( i, T );        if( Retrieve( T ) == i )            printf( "Error3 at %d\n", i );    }

    printf( "Min is %d\n", Retrieve( T = FindMin( T ) ) );    printf( "Max is %d\n", Retrieve( T = FindMax( T ) ) );

Page 42: DS

42

    return 0;}