Data Structure Lab Mannual for 3rd Sem IT Department

89
INDEX EX.NO DATE PROGRAM SIGNATURE 1 6.7.10 SINGLY LINKED LIST 2 20.7.10 DOUBLY LINKED LIST 3 3.8.10 POLYNOMIAL ADDITION 4 10.8.10 INFIX TO POSTFIX CONVERSION 5 17.8.10 PRODUCER-CONSUMER PROBLEM 6 24.8.10 EXPRESSION TREE 7 31.8.10 BINARY SEARCH TREE 8 7.9.10 PRIORITY QUEUE 9 14.9.10 HASHING 10 21.9.10 DIJKSTRA’S ALGORITHM 11 28.9.10 KNAPSACK PROBLEM 1

Transcript of Data Structure Lab Mannual for 3rd Sem IT Department

Page 1: Data Structure Lab Mannual for 3rd Sem IT Department

INDEX

EX.NO DATE PROGRAM SIGNATURE

1 6.7.10 SINGLY LINKED LIST

2 20.7.10 DOUBLY LINKED LIST

3 3.8.10 POLYNOMIAL ADDITION

4 10.8.10 INFIX TO POSTFIX CONVERSION

5 17.8.10 PRODUCER-CONSUMER PROBLEM

6 24.8.10 EXPRESSION TREE

7 31.8.10 BINARY SEARCH TREE

8 7.9.10 PRIORITY QUEUE

9 14.9.10 HASHING

10 21.9.10 DIJKSTRA’S ALGORITHM

11 28.9.10 KNAPSACK PROBLEM

1

Page 2: Data Structure Lab Mannual for 3rd Sem IT Department

SINGLY LINKED LISTExpt.no: 1

Date:

AIM:To write a C program to implement singly linked list.

ALGORITHM:

1. Define a node with data and Next(pointer) fields using structure.

2. List the list of operations of linked list.

1.create 2.insert 3.Delete 4.search 5.print

3. Get the choice ch.

4. If ch=1 go to step 5. Else go to step 9.

5. Get the data and allocate a memory for a Node.

6. Assign data and NULL pointer to the node.

7. If the list is empty , make new node as head node. else assign address of New

node to Pointer field of last node.

8. To add more data go to step 5. Else go to step 9.

9. If ch=2, go to step 10 else go to 13.

10. Get the data to insert in item and the data before which to insert in t.

11. Find Node curr with data x and previous node prev of Node curr.

12. Assign the address of new node to Next field of prev and curr to Next field of

New node.

13. If ch=3 go to step 14 else go to step 16 .

14. Get the data to delete. Find the node curr with that data and prev of curr.

15. Assign next field value of curr to next field value of prev and delete curr.

16. If ch=4 scan all the node from the gead node till match is found

17. If ch=5 scan all the Nodes from head Node and print the values of Node.

Note: Next field of Node gives address of next node in the list.

PROGRAM:

2

Page 3: Data Structure Lab Mannual for 3rd Sem IT Department

#include <stdio.h>

#include <stdlib.h>

struct node /* structure of the node*/

{

int data;

struct node *link;

};

struct node *start=NULL;

struct node *temp,*prev, *nod;

void insert(struct node *);

void delet();

void display();

int main(void)

{

int opt;

clrscr();

do

{

printf("\n 1.Insert element into a singly linked list\n");

printf("\n 2.Delete element from a singly linked list\n");

printf("\n 3.Display list\n");

printf("\n 4.Quit\n");

printf("\nEnter option: ");

scanf("%d",&opt);

switch(opt)

{

3

Page 4: Data Structure Lab Mannual for 3rd Sem IT Department

case 1:

nod=(struct node *)calloc(1,sizeof(struct node));

insert(nod);

break;

case 2:

delet();

break;

case 3:

display();

break;

case 4:

exit(1);

}

}

while(1);

}

void insert(struct node *n) /* Insert operation*/

{

int item;

printf("\nEnter the element that has to be inserted: ");

scanf("%d",&item);

n->data=item;

if(start==NULL)

{

start= n;

n->link =0;

}

4

Page 5: Data Structure Lab Mannual for 3rd Sem IT Department

else /* search list to insert element in order*/

{

temp = start;

while (temp != 0)

{

if (temp->data < item)

{

prev = temp;

temp = temp->link;

}

else break;

}

if (temp == start) /* if the element is to be inserted as the first node*/

{

n->link = temp;

start = n;

}

else /* if the element is to be inserted elsewhere in the list*/

{

prev->link = n;

n->link = temp;

}

}

}

void delet() /* delete operation*/

{

int item;

5

Page 6: Data Structure Lab Mannual for 3rd Sem IT Department

printf("\nEnter the element that has to be deleted: ");

scanf("%d",&item);

if(start==NULL)

printf("\n List is empty! No deletion possible! \n");

else

{

temp = start;

while (temp != 0)

{

if (temp->data == item) break;

else

{ prev = temp;

temp = temp->link;

}

}

if (temp == start) /* if the element to be deleted is the first node*/

{ start = temp->link;

free(temp);

}

else /*end of list encountered-element not found*/

{ if (temp == 0)

{printf(" Item not found in the list\n");}

else

{ prev->link = temp->link; /*reset links to delete*/

free(temp);

6

Page 7: Data Structure Lab Mannual for 3rd Sem IT Department

}

}

}

}

void display() /*display list */

{

if(start == NULL)

printf("\n List is empty! \n");

else

{printf("contents of the List: \n");

temp=start;

while(temp->link !=0)

{

printf("\n %d ",temp->data);

temp=temp->link; }

printf("\n %d ",temp->data);

}

}

OUTPUT :

7

Page 8: Data Structure Lab Mannual for 3rd Sem IT Department

1.Insert element into a singly linked list

2.Delete element from a singly linked list

3.Display list

4.Quit

Enter option:1

Enter the element that has to be inserted: 2

1.Insert element into a singly linked list

2.Delete element from a singly linked list

3.Display list

4.Quit

Enter option:1

Enter the element that has to be inserted: 4

1.Insert element into a singly linked list

2.Delete element from a singly linked list

3.Display list

4.Quit

Enter option: 3

contents of the List:

2

4

1.Insert element into a singly linked list

2.Delete element from a singly linked list

3.Display list

4.Quit

Enter option: 2

Enter the element that has to be deleted:2

1.Insert element into a singly linked list

2.Delete element from a singly linked list

3.Display list

8

Page 9: Data Structure Lab Mannual for 3rd Sem IT Department

4.Quit

Enter option: 3

contents of the List:

4

1.Insert element into a singly linked list

2.Delete element from a singly linked list

3.Display list

4.Quit

Enter option: 4

RESULT:

Thus the program for singly linked list has been written and executed successfully.

DOUBLY LINKED LIST

9

Page 10: Data Structure Lab Mannual for 3rd Sem IT Department

Expt.no:2

Date:

AIM:To write a C program to implement doubly linked list.

ALGORITHM:

1. Define a node with data and Next(pointer) and prev fields using structure.

2. List the list of operations of linked list.

1.create 2.insert 3.Delete 4.search 5.print

3. Get the choice ch.

4. If ch=1 go to step 5. Else go to step 9.

5. Get the data and allocate a memory for a Node.

6. Assign data to data fiels and NULL pointers to both next and prev of the node.

7. If the list is empty , make new node as head node. else assign address of New

node to Next field of last node and address of last node to prev field of new Node.

8. To add more data go to step 5. Else go to step 9.

9. If ch=2, go to step 10 else go to 12.

10. Get the data to insert in item and the data before which to insert in item.

11. Find Node curr with data x. and assign temp->item=item; temp->next=cur;

temp->prev=curr->prev; cur->prev->next=temp;.

12. If ch=3 go to step 13 else go to step 15 .

13. Get the data to delete. Find the node curr with that data.

14. Assign cur->prev->next=cur->next and delete the node curr ;

15. If ch=4 scan all the node from the gead node till match is found

16. If ch=5 scan all the Nodes from head Node and print the values of Node.

Note: Next field of Node gives address of next node in the list. No need to find

the address of previous node as in singly linked list

PROGRAM:

#include<stdio.h>

10

Page 11: Data Structure Lab Mannual for 3rd Sem IT Department

#include<conio.h>

typedef struct List

{

int item;

struct List *next;

struct List *prev;

}Node;

void main()

{

int item,ch;

void create(Node*);

void insert(Node*,int);

void delitem(Node*,int);

int search(Node*,int);

Node* findnode(Node*,int);

void print(Node*);

Node *head=(Node*) malloc(sizeof(Node));

head->next=NULL;

clrscr();

while(1)

{

getch();

clrscr();

printf("\n 1.create \n 2.insert \n 3.Delete \n 4.search \n 5. print\n

6.Exit\n");

printf("What's ypur choice: ");

scanf("%d",&ch);

switch(ch)

{

case 1:

create(head);

break;

case 2:

printf("\n Enter the item to insert:");

11

Page 12: Data Structure Lab Mannual for 3rd Sem IT Department

scanf("%d",&item);

insert(head,item);

break;

case 3:

printf("\n Enter the item:");

scanf("%d",&item);

delitem(head,item);

break;

case 4:

printf("\n Enter the item: ");

scanf("%d",&item);

if(search(head,item))

printf("\n Item Found");

else

printf("\n Item Not found");

break;

case 5:

print(head);

break;

case 6:

exit(0);

default:

printf("\n Invalid option");

}

}

}

int search(Node *head, int item)

{

int i=0;

Node *temp=head->next;

while(temp!=NULL)

{

12

Page 13: Data Structure Lab Mannual for 3rd Sem IT Department

if(temp->item==item)

{

i=1;

break;

}

else

temp=temp->next;

}

return i;

}

void create(Node *new1)

{

int item;

Node* new2;

printf("Enter the Element[-99 to exit]: ");

scanf("%d",&item);

if( item!= -99)

{

new2=(Node*) malloc(sizeof(Node));

new2->item=item;

new2->next=NULL;

new2->prev=new1;

new1->next=new2;

create(new2);

}

}

Node* findnode(Node* head,int item)

{

Node* temp=head;

while( temp->next!=NULL && temp->item!=item)

temp=temp->next;

return temp;

}

13

Page 14: Data Structure Lab Mannual for 3rd Sem IT Department

void delitem(Node* head,int item)

{

Node *cur,*temp;

cur=findnode(head,item);

temp=cur;

cur->prev->next=cur->next;

free(temp);

printf("\n Deleted");

}

void insert(Node* head,int item)

{

int t;

Node* cur,*temp;

printf("\n Enter the item before which you want to insert:");

scanf("%d",&t);

cur=findnode(head,t);

temp=(Node*) malloc(sizeof(Node));

temp->item=item;

temp->next=cur;

temp->prev=curr->prev

cur->prev->next=temp;

}

void print(Node* head)

{

Node* temp=head->next;

while(temp!=NULL){

printf("%d ",temp->item);

temp=temp->next; }

}

OUTPUT:

1.create

14

Page 15: Data Structure Lab Mannual for 3rd Sem IT Department

2.insert

3.Delete

4.search

5. print

6.Exit

What's ypur choice: 1

Enter the Element[-99 to exit]: 1

Enter the Element[-99 to exit]: 2

Enter the Element[-99 to exit]: 4

Enter the Element[-99 to exit]: -99

1.create

2.insert

3.Delete

4.search

5. print

6.Exit

What's ypur choice: 5

1 2 4

1.create

2.insert

3.Delete

4.search

5. print

6.Exit

What's ypur choice: 2

Enter the item to insert:3

Enter the item before which you want to insert:4

1.create

2.insert

15

Page 16: Data Structure Lab Mannual for 3rd Sem IT Department

3.Delete

4.search

5. print

6.Exit

What's ypur choice: 5

1 2 3 4

1.create

2.insert

3.Delete

4.search

5. print

6.Exit

What's ypur choice: 3

Enter the item:3

Deleted

1.create

2.insert

3.Delete

4.search

5. print

6.Exit

What's ypur choice: 4

Enter the item: 3

Item Not found

RESULT:

Thus the program for doubly linked list has been written and executed successfully.

POLYNOMIAL ADDITIONExpt no:3

Date:

16

Page 17: Data Structure Lab Mannual for 3rd Sem IT Department

AIM:

To write a C program to add two polynomial functions.

ALGORITHM:

1. Define a Node with coeff,exp and Next(pointer) fields.

2. Get all the terms ( coeff & exp) of polynomial function f(x) and create a create a

linked list.

3. Get all the terms ( coeff & exp) of polynomial function g(x) and create a create a

linked list.

4. Compare the terms of both f(x) and g(x).

5. If exp values of both are equal then add eoeff values and create a new linked list

with added values.

6. If no exp match just include the term in the new list as such.

7. Print the values of all 3 list.

PROGRAM:

#include<stdio.h>

17

Page 18: Data Structure Lab Mannual for 3rd Sem IT Department

#include<conio.h>

typedef struct List

{

int coeff;

int exp;

struct List *next;

}Node;

void main()

{

Node* poly1,*poly2,*poly3;

void create(Node*);

void print(Node*);

void addpolynomial(Node*,Node*,Node*);

poly1=(Node*) malloc(sizeof(Node));

poly2=(Node*) malloc(sizeof(Node));

poly3=(Node*) malloc(sizeof(Node));

clrscr();

printf("\n Enter f(x) : ");

create(poly1);

printf("\n\n Enter g(x): " );

create(poly2);

addpolynomial(poly1,poly2,poly3);

printf("\n\n f(x) : ");

print(poly1);

printf("\n\n g(x) : ");

print(poly2);

printf("\n\n Result : ");

print(poly3);

getch();

}

void addpolynomial(Node* poly1,Node* poly2, Node* poly3)

{

Node* temp1,*temp2,*temp3,*temp;

int flag=0;

18

Page 19: Data Structure Lab Mannual for 3rd Sem IT Department

temp3=poly3;

temp1=poly1->next;

temp2=poly2->next;

while( temp1!=NULL)

{

while(temp2!=NULL)

{

if(temp1->exp==temp2->exp)

{

temp=(Node*) malloc(sizeof(Node));

temp->coeff= temp1->coeff + temp2->coeff;

temp->exp=temp1->exp;

temp->next=NULL;

temp3->next=temp;

temp3=temp;

temp2=temp2->next;

break;

}

else if(temp1->exp>temp2->exp)

{

temp=(Node*) malloc(sizeof(Node));

temp->coeff= temp1->coeff ;

temp->exp=temp1->exp;

temp->next=NULL;

temp3->next=temp;

temp3=temp;

break;

}

else

{

temp=(Node*) malloc(sizeof(Node));

temp->coeff= temp2->coeff;

temp->exp=temp2->exp;

temp->next=NULL;

19

Page 20: Data Structure Lab Mannual for 3rd Sem IT Department

temp3->next=temp;

temp3=temp;

flag=1;

temp2=temp2->next;

break;

}

}

if(flag==1)

{

flag=0;

continue;

}

temp1=temp1->next;

}

}

void create(Node* poly)

{

char str1[30],str2[10],dt[5];

int i,j=0,coeff,exp;

Node* temp1,*temp2;

temp1=poly;

scanf("%s",str1);

for(i=0;str1[i]!='\0';i++)

{

if(str1[i] != 'x' && str1[i] != '+')

dt[j++]=str1[i];

else if(str1[i]=='x')

{

dt[j]='\0';

coeff=atoi(dt);

j=0;

}

else if(str1[i]=='+')

{

20

Page 21: Data Structure Lab Mannual for 3rd Sem IT Department

dt[j]='\0';

exp=atoi(dt);

if(exp==0)

exp=1;

j=0;

temp2=(Node*) malloc(sizeof(Node));

temp2->coeff=coeff;

temp2->exp=exp;

temp2->next=NULL;

temp1->next=temp2;

temp1=temp2;

}

}

dt[j]='\0';

coeff=atoi(dt);

temp2=(Node*) malloc(sizeof(Node));

temp2->coeff=coeff;

temp2->exp=0;

temp2->next=NULL;

temp1->next=temp2;

}

void print(Node* head)

{

Node* temp=head->next;

while(temp!=NULL)

{

if(temp->exp==1)

printf("%dx + ",temp->coeff);

else if(temp->exp==0)

printf("%d\n",temp->coeff);

else

printf("%dx^%d + ",temp->coeff,temp->exp);

temp=temp->next;

21

Page 22: Data Structure Lab Mannual for 3rd Sem IT Department

}

}

OUTPUT:

22

Page 23: Data Structure Lab Mannual for 3rd Sem IT Department

Enter f(x) : 4x4+4x+4

Enter g(x): 3x3+3x2+3x+3

f(x) : 4x^4 + 4x + 4

g(x) : 3x^3 + 3x^2 + 3x + 3

Result : 4x^4 + 3x^3 + 3x^2 + 7x + 7

RESULT:

Thus the program to add polynomial function has been witten and executed

successfully.

INFIX TO POSTFIX CONVERSIONExpt.no:4

23

Page 24: Data Structure Lab Mannual for 3rd Sem IT Department

Date:

AIM:

To write a C program to convert infix expression into postfix form.

ALGORITHM:

1. Get the infix expression.

2. Initialize the postfix expr to NULL;

3. Read the symbol of infix expression.

4. If the input symbol is operand add the symbol directly on to the postfix expr.

5. If the symbol is operator compare the precedence of this operator with operator at

the top of the stack

6. If the input symbol’s precedence is lower, pop the element at TOS and append it

to postfix expr and go to step 5. Else push the input symbol at TOS.[ if symbol at

TOS is ‘(‘ no need to compare the precedence].

7. If symbol is ‘)’ pop all elements till ‘)’ and append to postfix expr. Pop ‘)’ and

neglect it.

8. If still more symbol in the infix expr go to step 3 else go to step 9.

9. Print both infix and postfix expressions.

PROGRAM:

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

24

Page 25: Data Structure Lab Mannual for 3rd Sem IT Department

struct Stack{

int maxtop;int top;char values[20];

} s;int main(){

int p1,p2,i,j=0,k;char t,infix[30],postfix[30];char opr[5]={'+','-','*','/','('};int prec[5]={1,1,2,2,3};void push(const char x);char pop();clrscr();s.top=-1;s.maxtop=10;printf("Enter the infix expression: ");scanf("%s",infix);for (i=0;infix[i]!='\0';i++){

if( isalnum(infix[i]))postfix[j++]=infix[i];

else if(infix[i]==')'){

for(k=s.top; (t=pop()) != '(';k--)postfix[j++]= t;

}else{

if ( s.top == -1){

push(infix[i]);continue;

}t=s.values[s.top];for(k=0;k<5;k++){

if( t==opr[k]) p1=prec[k];if(infix[i]==opr[k]) p2=prec[k];

}if(p2>p1|| t=='(')

push(infix[i]);else{

postfix[j++]=pop();push(infix[i]);

}}

}

25

Page 26: Data Structure Lab Mannual for 3rd Sem IT Department

for(i=s.top;i>=0;i--)

postfix[j++]=pop();

postfix[j]='\0';

printf("postfix form:%s ",postfix);

getch();

return 0;}void push(const char x){

if (s.top!=s.maxtop)s.values[++s.top] = x;

}char pop(){

if (s.top!=-1)return s.values[s.top--];

elsereturn NULL;

}

OUTPUT:

26

Page 27: Data Structure Lab Mannual for 3rd Sem IT Department

Enter the infix expression: a+(b-c)*d

postfix form: abc-d*+

RESULT:

Thus the program to convert infix expression into postfix form has been written and executed successfully.

PRODUCER-CONSUMER PROBLEMExpt no:5

27

Page 28: Data Structure Lab Mannual for 3rd Sem IT Department

Date :

AIM:

To write a C program to implement producer consumer problem using array based

circular queue.

ALGORITHM:

1. Let SIZE be the size of Queue and let the Queue be empty.

2. Let both front and rear pointers points to the beginning of Q.

3. Generate a random number x using random() function.

4. If the Q is not full, add x to the Q where the rear pointer is pointing to. And

increment the rear pointer by 1[ front=(front+1)%SIZE]. Go to step 3.

5. if the Q is not empty dequeue the element from Q where the front pointer is

pointing to. And increment the front by 1.[ front=(front+1)%SIZE].

6. To dequeue again go to step 5. To enqueue go to step 3.

Note:

Producer always produce items if there is a room in Q.

Consumer always consumes item if there is element in Q.

In reality both producer and consumer are concurrent processes.

PROGRAM:

#include<stdio.h>

28

Page 29: Data Structure Lab Mannual for 3rd Sem IT Department

#include<conio.h>

#include<stdlib.h>

#define SIZE 3

struct Queue

{

int a[SIZE];

int front,rear,count;

}q;

int main()

{

int i,choice,value;

char ch;

void producer();

int consumer();

q.front=q.rear=q.count=0;

clrscr();

do

{

printf("\n 1.produce");

printf("\n 2.consume");

printf("\n Enter the choice:");

scanf("%d",&choice);

if(choice==1)

producer();

else if(choice==2)

{

value=consumer();

if(value!=-1)

printf("\nvalue consumed = %d",value);

}

else

printf("invalid choice");

printf("\n Do you want to continue:");

ch=getche();

29

Page 30: Data Structure Lab Mannual for 3rd Sem IT Department

}while( ch=='y'||ch=='Y');

getch();

return 0;

}

void producer()

{

int t,i,r;

randomize();

for(; q.count<SIZE;)

{

t=random(1000);

q.a[q.rear]=t;

q.rear=(q.rear+1)%SIZE;

q.count++;

}

printf("ITEMS produced are: ");

for(i=0;i<SIZE;i++)

printf("%d ",q.a[i]);

printf("Queue is FULL\n");

}

int consumer()

{

int t=-1;

if( q.count != 0)

{

t=q.a[q.front];

q.front=(q.front+1)%SIZE;

q.count--;

}

else

printf("\n Queue is Empty");

return t;

30

Page 31: Data Structure Lab Mannual for 3rd Sem IT Department

}

OUTPUT:

1.produce

31

Page 32: Data Structure Lab Mannual for 3rd Sem IT Department

2.consume

Enter the choice:2

Queue is Empty

Do you want to continue:y

1.produce

2.consume

Enter the choice:

1

Queue is FULL

ITEMS produced are: 502 577 459

Do you want to continue:y

1.produce

2.consume

Enter the choice:2

value = 502

Do you want to continue:y

1.produce

2.consume

Enter the choice:1

Queue is FULL

ITEMS produced are: 577 459 517

Do you want to continue:n

RESULT:

Thus the C program to implement producer consumer has been written and executed

successfully.

EXPRESSION TREEExpt.no:6

Date:

32

Page 33: Data Structure Lab Mannual for 3rd Sem IT Department

AIM:To write a C program to implement expression tree and produce in-

order,pre-order,post-order traversals.

ALGORITHM:

1. Define a Node with data and left and right(pointers).

2. Get the infix expression.

3. Convert the infix expr into postfix expr.

4. Read the symbol form the infix expression.

5. If the symbol is operand create a Node for the symbol and push the address of

Node into the stack.

6. If the symbol is operator, create the Node for symbol and assign its right and left

Childs be top two pointers of the stack.

7. Push the address of New node to stack.

8. To get next symbol go to step 4. Else the alone pointer in the stack gives the

address of root element of the expression tree.

9. To print in-order: scan Nodes in the order of left-node-right

10. To print pre-order: scan Nodes in the order of node-left-right

11. To print post-order: scan Nodes in the order of left-right-node

PROGRAM:

#include<stdio.h>

33

Page 34: Data Structure Lab Mannual for 3rd Sem IT Department

#include<conio.h>

typedef struct List

{

char item;

struct List *left;

struct List *right;

}Node;

struct Stack

{

int maxtop;

int top;

Node *values[20];

} s;

struct oprstack

{

int maxtop;

int top;

char values[20];

} s1;

void push(const Node* x)

{

if (s.top!=s.maxtop)

s.values[++s.top] =(Node*) x;

}

Node* pop()

{

if (s.top!=-1)

return s.values[s.top--];

else

return NULL;

}

void push1(const char x)

{

34

Page 35: Data Structure Lab Mannual for 3rd Sem IT Department

if (s1.top!=s1.maxtop)

s1.values[++s1.top] = x;

}

char pop1()

{

if (s1.top!=-1)

return s1.values[s1.top--];

else

return NULL;

}

void inorder( Node *t)

{

if(t!=NULL)

{

inorder(t->left);

printf("%c",t->item);

inorder(t->right);

}

}

void preorder( Node *t)

{

if(t!=NULL)

{

printf("%c",t->item);

preorder(t->left);

preorder(t->right);

}

}

void postorder( Node *t)

{

if(t!=NULL)

35

Page 36: Data Structure Lab Mannual for 3rd Sem IT Department

{

postorder(t->left);

postorder(t->right);

printf("%c",t->item);

}

}

void main()

{

char infix[20],postfix[20],t,p1,p2;

int i,j=0,k;

Node* t1,*t2,*t3;

char opr[5]={'+','-','*','/','('};

int prec[5]={1,1,2,2,3};

s1.top=-1;

s1.maxtop=20;

s.top=-1;

s.maxtop=20;

clrscr();

printf("Enter the infix expression: ");

gets(infix);

for (i=0;infix[i]!='\0';i++)

{

if( isalnum(infix[i]))

postfix[j++]=infix[i];

else if(infix[i]==')')

{

for(k=s1.top; (t=pop1()) != '(';k--)

postfix[j++]=(char) t;

}

else

{

if ( s1.top == -1)

{

36

Page 37: Data Structure Lab Mannual for 3rd Sem IT Department

push1(infix[i]);

continue;

}

t=s1.values[s1.top];

for(k=0;k<5;k++)

{

if( t==opr[k]) p1=prec[k];

if(infix[i]==opr[k]) p2=prec[k];

}

if(p2>p1|| t=='(')

push1(infix[i]);

else

{

postfix[j++]=pop1();

push1(infix[i]);

}

}

}

for(i=s1.top;i>=0;i--)

postfix[j++]=pop1();

postfix[j]='\0';

for(i=0;postfix[i]!='\0';i++)

{

if( isalpha(postfix[i]))

{

t1=(Node*) malloc(sizeof(Node));

t1->item=postfix[i];

t1->left=NULL;

t1->right=NULL;

push(t1);

}

else

37

Page 38: Data Structure Lab Mannual for 3rd Sem IT Department

{

t2=pop();

t3=pop();

t1=(Node*) malloc(sizeof(Node));

t1->item=postfix[i];

t1->left=t3;

t1->right=t2;

push(t1);

}

}

t1=pop();

printf("inorder: ");

inorder(t1);

printf("\npreorder: ");

preorder( t1);

printf("\npostorder: ");

postorder(t1);

getch();

}

OUTPUT:

Enter the infix expression: a+(b-c)*d

38

Page 39: Data Structure Lab Mannual for 3rd Sem IT Department

inorder: a+b-c*d

preorder: +a*-bcd

postorder: abc-d*+

RESULT:

Thus the program for expression tree has been written and executed

successfully.

BINARY SEARCH TREEExpt.no:7

Date:

39

Page 40: Data Structure Lab Mannual for 3rd Sem IT Department

AIM:

To write a C program to implement binary search tree operations.

ALGORITHM:

1. Define a Node with data and left and right(pointers) fields using structures.

2. Let the tree T be empty.

3. Get the value X for the Node. create a Node and assign data= X,

left=right=NULL.

4. If the T is empty make new Node as root.

5. If T is not empty, locate a smallest Node S that is larger than New Node.

6. If X < S , make the new Node be the left child of S else make it be right child.

7. To insert more data go to step 3.

8. To delete, get the data to be deleted.

9. Locate the desired Node in the tree.

10. If the node is a leaf, Delete it immediately. Make either left/child of parent be

NULL.

11. If the node has one child, Adjust a pointer from the parent to bypass that node

12. If the node has 2 children,Replace the key of that node with the minimum

element at the right subtree and Delete that minimum element.

13. To find Minimum element in T, print the left most Node in leaf level

14. To find Maximum element in T, print theright most Node in leaf level

Note:

In BST, left child of Node is less than its root and right child is greater than or

equal to its root.

PROGRAM:

40

Page 41: Data Structure Lab Mannual for 3rd Sem IT Department

/*Insertion ,Deletion in Binary Search Tree*/

# include<stdio.h>

# include<conio.h>

struct node

{

int info;

struct node *lchild;

struct node *rchild;

}*root;

main()

{

int choice,num;

struct node* delet(int, struct node*);

struct node* insert(int x,struct node* );

root=NULL;

clrscr();

while(1)

{

printf("\n");

printf("1.Insert\n");

printf("2.Delete\n");

printf("3.Display\n");

printf("4.Quit\n");

printf("Enter your choice : ");

scanf("%d",&choice);

switch(choice)

{

case 1:

printf("Enter the number to be inserted: ");

scanf("%d",&num);

root=insert(num,root);

break;

case 2:

41

Page 42: Data Structure Lab Mannual for 3rd Sem IT Department

printf("Enter the number to be deleted : ");

scanf("%d",&num);

delet(num,root);

break;

case 3:

display(root,1);

break;

case 4:

exit();

default:

printf("Wrong choice\n");

}/*End of switch */

getch();

}/*End of while */

}/*End of main()*/

struct node* insert(int x,struct node* t)

{

if(t==NULL)

{

t = (struct node*)malloc(sizeof(struct node));

t->info = x;

t->lchild = t->rchild = NULL;

}

else

{

if(x < t->info)

t->lchild =(struct node*) insert(x, t->lchild);

else if(x > t->info)

t->rchild = (struct node*) insert(x, t->rchild);

}

return t;

}

42

Page 43: Data Structure Lab Mannual for 3rd Sem IT Department

struct node* findmin(struct node* temp)

{

if(temp == NULL || temp->lchild == NULL)

return temp;

return findmin(temp->lchild);

}

struct node* delet(int x,struct node* t)

{

struct node* temp;

if(t == NULL)

printf("\nElement not found");

else

{

if(x < t->info)

t->lchild =(struct node*) delet(x, t->lchild);

else if(x > t->info)

t->rchild = delet(x, t->rchild);

else

{

if(t->lchild && t->rchild)

{

temp = findmin(t->rchild);

t->info = temp->info;

t->rchild = delet(t->info,t->rchild);

}

else

{

temp=t;

if(t->lchild == NULL)

t=t->rchild;

else

t=t->lchild;

43

Page 44: Data Structure Lab Mannual for 3rd Sem IT Department

free(temp);

}

}

}

return t;

}

display(struct node *ptr,int level)

{

int i;

if ( ptr!=NULL )

{

display(ptr->rchild, level+1);

printf("\n");

for (i = 0; i < level; i++)

printf(" ");

printf("%d", ptr->info);

display(ptr->lchild, level+1);

}/*End of if*/

return;

}/*End of display()*/

OUTPUT:

44

Page 45: Data Structure Lab Mannual for 3rd Sem IT Department

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 1

Enter the number to be inserted: 5

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 1

Enter the number to be inserted: 7

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 1

Enter the number to be inserted: 3

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 1

Enter the number to be inserted: 8

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 3

45

Page 46: Data Structure Lab Mannual for 3rd Sem IT Department

8

7

5

3

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 2

Enter the number to be deleted : 5

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 3

8

7

3

1.Insert

2.Delete

3.Display

4.Quit

Enter your choice : 4

RESULT:

Thus the program for binary search tree has been written and

executed successfully.

PRIORITY QUEUE

Expt.no:8

46

Page 47: Data Structure Lab Mannual for 3rd Sem IT Department

Date:

AIM:

To write a C program to implement priority queue using heaps.

ALGORITHM:

Let i be the pointer pointing to current node in heap.

i/2 ------ is parent.

2*i ------ is left child.

2*i+1---- is right child.

1. Set the Capacity of the Queue

2. Let SIZE =0 be the Current size of the Queue.

3. Get the data X to be inserted into the Queue.

4. If Q is not full go to step 5. else goto

5. Insert X into the next available location in the Queue and increment size by 1.

6. Compare X with parent of X.

7. If parent(X)> X, swap the values of these 2 nodes.

8. Continue step 6 and 7 till the parent be the root node.

9. To delete , remove element form the root.

10. Move the Smaller child to the root. Continue this till all nodes satisfies the heap

property.

11. Move the last node to the vacant position the heap.

Note:

In heap tree, both left and right child should be greater than the parent.

Nodes should be filled from left to right i.e tree should be complete.

PROGRAM:

47

Page 48: Data Structure Lab Mannual for 3rd Sem IT Department

#include <stdlib.h>

#define MinPQSize (10)

#define MinData (-32767)

typedef int ElementType;

struct HeapStruct

{

int Capacity;

int Size;

ElementType *Elements;

};

typedef struct HeapStruct *PriorityQueue;

PriorityQueue Initialize( ElementType MaxElements )

{

PriorityQueue H;

if( MaxElements < MinPQSize )

printf( "Priority queue size is too small" );

H = malloc( sizeof( struct HeapStruct ) );

if( H ==NULL )

printf( "Out of space!!!" );

/* Allocate the array plus one extra for sentinel */

H->Elements = malloc( ( MaxElements + 1 )* sizeof( ElementType ) );

if( H->Elements == NULL )

printf( "\n Out of space!!!" );

H->Capacity = MaxElements;

H->Size = 0;

H->Elements[ 0 ] = MinData;

return H;

}

/* END */

void MakeEmpty( PriorityQueue H )

{

48

Page 49: Data Structure Lab Mannual for 3rd Sem IT Department

H->Size = 0;

}

/* H->Element[ 0 ] is a sentinel */

void Insert( ElementType X, PriorityQueue H )

{

int i;

if( IsFull( H ) )

{

printf( "\nPriority queue is full" );

return;

}

for( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 )

H->Elements[ i ] = H->Elements[ i / 2 ];

H->Elements[ i ] = X;

}

/* END */

ElementType DeleteMin( PriorityQueue H )

{

int i, Child;

ElementType MinElement, LastElement;

if( IsEmpty( H ) )

{

printf( "\nPriority queue is empty" );

return H->Elements[ 0 ];

}

MinElement = H->Elements[ 1 ];

LastElement = H->Elements[ H->Size-- ];

for( i = 1; i * 2 <= H->Size; i = Child )

{

/* Find smaller child */

Child = i * 2;

49

Page 50: Data Structure Lab Mannual for 3rd Sem IT Department

if( Child != H->Size && H->Elements[ Child + 1 ]< H->Elements[

Child ] )

Child++;

/* Percolate one level */

if( LastElement > H->Elements[ Child ] )

H->Elements[ i ] = H->Elements[ Child ];

else

break;

}

H->Elements[ i ] = LastElement;

return MinElement;

}

/* END */

int IsEmpty( PriorityQueue H )

{

return H->Size == 0;

}

int IsFull( PriorityQueue H )

{

return H->Size == H->Capacity;

}

display( PriorityQueue H)

{

int i;

printf("Elements in priority Q....\n");

for(i=1;i<=H->Size;i++)

{

printf("%d ",H->Elements[i]);

}

return;

50

Page 51: Data Structure Lab Mannual for 3rd Sem IT Department

}/*End of display()*/

int main()

{

PriorityQueue H;

ElementType choice,num,MinElement;

int i,j;

H=Initialize(10);

clrscr();

while(1)

{

printf("\n1.insert");

printf("\n2.DeleteMin");

printf("\n3.Display");

printf("\n4.Quit");

printf("\n Enter the choice:");

scanf("%d",&choice);

switch(choice)

{

case 1:

printf("Enter the element: ");

scanf("%d",&num);

Insert( num,H);

break;

case 2:

MinElement=DeleteMin(H);

printf("\n Minimum Element: %d is

deleted",MinElement);

break;

case 3:

T=H;

display(1);

break;

case 4:

51

Page 52: Data Structure Lab Mannual for 3rd Sem IT Department

exit(0);

}

}

}

OUTPUT:

52

Page 53: Data Structure Lab Mannual for 3rd Sem IT Department

1.insert

2.DeleteMin

3.Display

4.Quit

Enter the choice:1

Enter the element: 9

1.insert

2.DeleteMin

3.Display

4.Quit

Enter the choice:1

Enter the element: 15

1.insert

2.DeleteMin

3.Display

4.Quit

Enter the choice:1

Enter the element: 12

1.insert

2.DeleteMin

3.Display

4.Quit

Enter the choice:3

Elements in priority Q....

9 15 12

1.insert

2.DeleteMin

3.Display

4.Quit

53

Page 54: Data Structure Lab Mannual for 3rd Sem IT Department

Enter the choice:2

Minimum Element: 9 is deleted

1.insert

2.DeleteMin

3.Display

4.Quit

Enter the choice:3

Elements in priority Q....

12 15

1.insert

2.DeleteMin

3.Display

4.Quit

Enter the choice:4

RESULT:

Thus the program to implement priority queue has been written and

executed successfully.

HASHING

54

Page 55: Data Structure Lab Mannual for 3rd Sem IT Department

Expt.no:9

Date:

AIM:To write a C program to implement a hashing technique.

ALGORITHM:

[ separate chaining method- To solve collision]

1. Initialize the hash table size.

2. Each location in the table has the address of linked list that has list of

items.

3. Get the key K to insert.

4. Generate the Hash value h using the hash function.

5. Use h as index in the hash table and find desired linked list and insert the

new key value as the first element in that list.

6. To add more keys goto step 3.

7. Move through the entire linked list in the hash table and print the values.

PROGRAM:

55

Page 56: Data Structure Lab Mannual for 3rd Sem IT Department

#include <stdio.h>

#include<conio.h>

#include <stdlib.h>

#define MinTableSize (10)

#define NumItems 100

typedef int ElementType;

typedef unsigned int Index;

typedef struct ListNode *Position;

struct ListNode

{

ElementType Element;

Position Next;

};

typedef Position List;

typedef struct HashTbl

{

int TableSize;

List *TheLists;

}*HashTable;

/* Return next prime; assume N >= 10 */

static int NextPrime( int N )

{

int i;

if( N % 2 == 0 )

N++;

for( ; ; N += 2 )

{

for( i = 3; i * i <= N; i += 2 )

56

Page 57: Data Structure Lab Mannual for 3rd Sem IT Department

if( N % i == 0 )

goto ContOuter; /* Sorry about this! */

return N;

ContOuter: ;

}

}

/* Hash function for ints */

Index Hash( ElementType Key, int TableSize )

{

return Key % TableSize;

}

HashTable InitializeTable( int TableSize )

{

HashTable H;

int i;

if( TableSize < MinTableSize )

{

printf( "\nTable size too small" );

return NULL;

}

/* Allocate table */

H = malloc( sizeof( struct HashTbl ) );

if( H == NULL )

printf( "\n Out of space!!!" );

H->TableSize = NextPrime( TableSize );

/* Allocate array of lists */

H->TheLists = malloc( sizeof( List ) * H->TableSize );

if( H->TheLists == NULL )

printf( "\nOut of space!!!" );

57

Page 58: Data Structure Lab Mannual for 3rd Sem IT Department

/* Allocate list headers */

for( i = 0; i < H->TableSize; i++ )

{

H->TheLists[ i ] = malloc( sizeof( struct ListNode ) );

if( H->TheLists[ i ] == NULL )

printf( "\nOut of space!!!" );

H->TheLists[ i ]->Next = NULL;

}

return H;

}

/* END */

Position Find( ElementType Key, HashTable H )

{

Position P;

List L;

L = H->TheLists[ Hash( Key, H->TableSize ) ];

P = L->Next;

while( P != NULL && P->Element != Key )

/* Probably need strcmp!! */

P = P->Next;

return P;

}

/* END */

Void Insert( ElementType Key, HashTable H )

{

Position Pos, NewCell;

List L;

Pos = Find( Key, H );

if( Pos == NULL ) /* Key is not found */

NewCell = malloc( sizeof( struct ListNode ) );

if( NewCell == NULL )

58

Page 59: Data Structure Lab Mannual for 3rd Sem IT Department

printf( "\n Out of space!!!" );

else

{

L = H->TheLists[ Hash( Key, H->TableSize ) ];

NewCell->Next = L->Next;

NewCell->Element = Key; /* Probably need strcpy! */

L->Next = NewCell;

}

}

/* END */

ElementType Retrieve( Position P )

{

return P->Element;

}

Void DestroyTable( HashTable H )

{

int i;

for( i = 0; i < H->TableSize; i++ )

{

Position P = H->TheLists[ i ];

Position Tmp;

while( P != NULL )

{

Tmp = P->Next;

free( P );

P = Tmp;

}

}

free( H->TheLists );

free( H );

}

main( )

59

Page 60: Data Structure Lab Mannual for 3rd Sem IT Department

{

HashTable H;

Position P;

int i,data,choice;

int CurrentSize;

H = InitializeTable( CurrentSize = 13 );

clrscr();

while(1)

{

printf("\n1.Insert");

printf("\n2.View Hashtable");

printf("\n3.Quit");

printf("\n Enter the choice: ");

scanf("%d",&choice);

switch(choice)

{

case 1:

printf("\n Enter the data: ");

scanf("%d",&data);

Insert(data,H);

break;

case 2:

clrscr();

for(i=0;i<H->TableSize;i++)

{

P=H->TheLists[i]->Next;

printf("\n%d: ",i);

for(; P!=NULL; P=P->Next)

printf("%d ",P->Element);

}

break;

case 3:

DestroyTable(H);

exit(0);

60

Page 61: Data Structure Lab Mannual for 3rd Sem IT Department

default:

printf("\n Wrong choice");

}

}

}

61

Page 62: Data Structure Lab Mannual for 3rd Sem IT Department

OUTPUT:

1.Insert

2.View Hashtable

3.Quit

Enter the choice: 1

Enter the data: 28

1.Insert

2.View Hashtable

3.Quit

Enter the choice: 1

Enter the data: 98

1.Insert

2.View Hashtable

3.Quit

Enter the choice: 1

Enter the data: 65

1.Insert

2.View Hashtable

3.Quit

Enter the choice: 1

Enter the data: 32

1.Insert

2.View Hashtable

3.Quit

Enter the choice: 2

0: 65

1:

2: 28

62

Page 63: Data Structure Lab Mannual for 3rd Sem IT Department

3:

4:

5:

6: 32

7: 98

8:

9:

10:

11:

12:

1.Insert

2.View Hashtable

3.Quit

Enter the choice:3

RESULT:

Thus the program to implement hashing has been written and executed successfully.

63

Page 64: Data Structure Lab Mannual for 3rd Sem IT Department

DIJKSTRA’S SHORTEST PATH ALGORITHM

Expt.no:10

Date:

AIM:

To write C program to implement Dijkstra’s shortest path algorithm.

ALGORITHM:

1. Get the adjacency matrix of the graph.

2. Let distance all node be infinity.

3. Select any one node as source node and let it be current node.

4. Compute the distance to all adjacent nodes from the current node.

5. If the newly computed distance for a node is shorter , then store this value as a

distance of that node.

6. Select Node with shortest distance and go to step 4.

7. Once distance of all the nodes are found, print the Node and its distance from the

source node.

64

Page 65: Data Structure Lab Mannual for 3rd Sem IT Department

PROGRAM:

#include <stdio.h>

#define MAX 4

#define INFINITE 998

int allselected(int *selected)

{

int i;

for(i=0;i<MAX;i++)

if(selected[i]==0)

return 0;

return 1;

}

void shortpath(int cost[][MAX],int *preced,int *distance)

{

int selected[MAX]={0};

int current=0,i,k,dc,smalldist,newdist;

for(i=0;i<MAX;i++)

distance[i]=INFINITE;

selected[current]=1;

distance[0]=0;

current=0;

while(!allselected(selected))

{

smalldist=INFINITE;

dc=distance[current];

for(i=0;i<MAX;i++)

{

if(selected[i]==0)

{

newdist=dc+cost[current][i];

if(newdist<distance[i])

65

Page 66: Data Structure Lab Mannual for 3rd Sem IT Department

{

distance[i]=newdist;

preced[i]=current;

}

if(distance[i]<smalldist)

{

smalldist=distance[i];

k=i;

}

}

}

current=k;

selected[current]=1;

}

}

int main()

{

int cost[MAX][MAX] ={{INFINITE,8,4,INFINITE},

{INFINITE,INFINITE,INFINITE,3} , {INFINITE,3,INFINITE,8},

{INFINITE,INFINITE,INFINITE,INFINITE}};

int i,preced[MAX]={0},distance[MAX];

clrscr();

shortpath(cost,preced,distance);

printf("vertex\t distance\n");

for(i=0;i<MAX;i++)

printf("%d\t %d\n",i+1,distance[i]);

getch();

return 0;

}

66

Page 67: Data Structure Lab Mannual for 3rd Sem IT Department

OUTPUT:

vertex distance

1 0

2 7

3 4

4 10

RESULT:

Thus the program for Dijkstra’s algorithm has been written and

executed successfully.

67

Page 68: Data Structure Lab Mannual for 3rd Sem IT Department

KNAPSACK PROBLEM

Expt.no:11

Date:

AIM:

To write C program to implement knapsack problem..

ALGORITHM:

1. Get no of items.

2. Get the cost(weight) and benefits of all items.

3. Get the Maximum capacity of the bag.

4. Add the items to the bag if there is room in the bag .

5. Add the item to the bag in certain order so that the bag contains maximum no of

items.

6. print the benefits and no of items in the bag.

68

Page 69: Data Structure Lab Mannual for 3rd Sem IT Department

PROGRAM:

#include <stdio.h>

int n = 5; /* The number of objects */

int c[10] = {12, 1, 2, 1, 4}; /* c[i] is the *COST* of the ith object;

i.e. what YOU PAY to take the object */

int v[10] = {4, 2, 2, 1, 10}; /* v[i] is the *VALUE* of the ith object;

i.e. what YOU GET for taking the object */

int W = 15; /* The maximum weight you can take */

void simple_fill()

{

int cur_w;

float tot_v=0;

int i, maxi;

int used[10];

for (i = 0; i < n; ++i)

used[i] = 0; /* I have not used the ith object yet */

cur_w = W;

while (cur_w > 0)

{ /* while there's still room*/

/* Find the best object */

maxi = -1;

for (i = 0; i < n; ++i)

if ((used[i] == 0) &&((maxi == -1) || ((float)c[i]/v[i] > float)c[maxi]/v[maxi])))

maxi = i;

used[maxi] = 1; /* mark the maxi-th object as used */

cur_w -= v[maxi]; /* with the object in the bag, I can carry less */

tot_v += c[maxi];

if (cur_w >= 0)

printf("Added object %d (%d$, %dKg) completly in the

bag. Space left: %d.\n", maxi + 1, c[maxi], v[maxi], cur_w);

69

Page 70: Data Structure Lab Mannual for 3rd Sem IT Department

else

{

tot_v -= c[maxi];

tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];

}

}

printf("Filled the bag with objects worth %.2f$.\n", tot_v);

}

int main()

{

clrscr();

simple_fill();

getch();

return 0;

}

70

Page 71: Data Structure Lab Mannual for 3rd Sem IT Department

OUTPUT:

Added object 1 (12$, 4Kg) completly in the bag. Space left: 11.

Added object 3 (2$, 2Kg) completly in the bag. Space left: 9.

Added object 4 (1$, 1Kg) completly in the bag. Space left: 8.

Added object 2 (1$, 2Kg) completly in the bag. Space left: 6.

Filled the bag with objects worth 16.00$.

RESULT:

Thus the program for knapsack problem has been written and executed

successfully.

71