0% found this document useful (0 votes)
12 views64 pages

DSA

Data Structure

Uploaded by

Nishchith
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views64 pages

DSA

Data Structure

Uploaded by

Nishchith
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 64

DATA STRUCTURES LABORATORY-BCSL305

/*1. Develop a Program in C for the following:


a) Declare a calendar as an array of 7 elements (A dynamically Created array) to
represent 7 days of a week. Each Element of the array is a structure having three
fields. The first field is the name of the Day (A dynamically allocated String),
The second field is the date of the Day (A integer), the third field is the
description of the activity for a particular day (A dynamically allocated String).
b) Write functions create(), read() and display(); to create the calendar, to read
the data from the keyboard and to print weeks activity details report on screen.*/

//Required Header files

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Define the structure for a day

struct Day {

char *name; // Dynamic string for day name

int date; // Integer for date

char *description; // Dynamic string for activity description

};

// Function to create the calendar

void create(struct Day calendar[7]) {

for (int i = 0; i < 7; i++) {


// dynamically allocate memory for the day name and description

calendar[i].name = (char *)malloc(50 * sizeof(char)); // Assuming max


length of day name is 50 characters

calendar[i].description = (char *)malloc(100 * sizeof(char)); // Assuming


max length of description is 100 characters

// Function to read the weekly activity details


void read(struct Day calendar[7]) {

for (int i = 0; i < 7; i++) {

printf("Enter name for Day %d: ", i + 1);

scanf("%s", calendar[i].name);

printf("Enter date for Day %d: ", i + 1);

scanf("%d", &calendar[i].date);

printf("Enter description for Day %d: ", i + 1);

scanf("%s", calendar[i].description);

// Function to display the weekly activity details

void display(struct Day calendar[7]) {

for (int i = 0; i < 7; i++) {

printf("Day Name: %s\n", calendar[i].name);

printf("Date: %d\n", calendar[i].date);

printf("Description: %s\n", calendar[i].description);

printf("\n");

}
}

int main() {

struct Day calendar[7];

// Call the create function to create the calendar

create(calendar);

read(calendar);

// Display the weekly activity details

printf("\nWeekly Activity Details:\n");

display(calendar);

// Free dynamically allocated memory

for (int i = 0; i < 7; i++) {

free(calendar[i].name);

free(calendar[i].description);

return 0;

2./* Design, Develop and Implement a Program in C for the following


operations on Strings

a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of
PAT in STR with REP if PAT exists in STR. Report suitable messages in case

PAT does not exist in STR

Support the program with functions for each of the above operations. Don't use
Built-in functions. */

#include<stdio.h>

// user defined parameterized functions prototype

int length(char[]);

int match(char[], char[], int, int);

int compare(char[], char[]);

// main ( ) to drive the code

void main()

// local declarations

char str[100], pat[100], rep[100], t[100], d[100];

int ls, lp, lr;

int i, j, l, l1=0, k=0;

// Read strings

printf("\n Enter main String :");

gets(str);

printf("\n Enter pattern String :");

gets(pat);

printf("\n Enter Replace String :");


gets(rep);

// find the length of strings

ls = length(str);

lp = length(pat);

lr = length(rep);

// check weather pattern matches or not

if (ls < lp || !match(str, pat, ls, lp))

printf("\n Pattern Not found!!!!\n");

else // if pattern matches

// Replaces all occurrences of pattern in string

for (i=0;i<ls;i++) // loop for the size of main string

for(j=0; j<lp; j++) // copy the first chunk form main string of
pattern length

t[j]=str[i+j]; // store in temporary string

t[j]='\0'; // end the temporary string

if (compare(t,pat)==0) // compare temporary string with pattern


string

k++; // count number of replaces

for(l=0;l<lr;l++)

d[l1++]=rep[l];
i=i+(lp-1);

else

d[l1++]=str[i];

d[l1]='\0'; // end of destination string

// display the results

printf("\n The number of string replaced =%d \n", k);

printf("\n Original String =%s \n", str);

printf("\n Pattern String =%s \n", pat);

printf("\n Replace String =%s \n", rep);

printf("\n String after replacement =%s \n", d);

// function to find the length of string

int length(char str[])

int i, len =0;

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

len++;

return len;

}
// function to compare two strings

int compare(char str1[],char str2[])

int i=0;

while (str1[i] == str2[i] && str1[i] != '\0')

i++;

if (str1[i] > str2[i])

return 1;

else if (str1[i] < str2[i])

return -1;

else

return 0; // both strings are same

// function to match pattern string in given string

int match(char text[], char pattern[], int ls, int lp)

int c, d, e;

for (c = 0; c <= ls - lp; c++) {

e = c;

for (d = 0; d < lp; d++)


{

if (pattern[d] == text[e])

e++;

else

break;

if (d == lp)

return 1; // return 1 if there is a pattern match

return 0; // return 0 if pattern does not found

/* 3. Design, Develop and Implement a menu driven Program in C for the


following operations on STACK of Integers (Array Implementation of Stack
with maximum size MAX)

a. Push an Element on to Stack

b. Pop an Element from Stack

c. Demonstrate how Stack can be used to check Palindrome

d. Demonstrate Overflow and Underflow situations on Stack

e. Display the status of Stack

f. Exit.

Support the program with appropriate functions for each of the above operations
*/

#include<stdio.h>

#define MAX 5
int stack[MAX];

int top=-1;

//a. Push an Element on to Stack

void push()

int item;

// Stack Overflow situations

if(top==(MAX-1))

printf("\n Stack Overflow");

else

printf("\n Enter the element to be pushed :");

scanf("%d",&item);

// pushing element to the top of stack

stack[++top]=item;

//b. Pop an Element from Stack

void pop()

// Stack Underflow situations


if(top==-1)

printf("\n Stack Underflow");

else

printf(" \nPoped element is %d ",stack[top--]); // poping element from the


top of stack

//e. Display the status of Stack

void display()

int i;

if(top==-1)

printf("\n Sorry Empty Stack");

else

printf("\nThe elements of the stack are\n");

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

printf("stack[%d] = %d\n",i, stack[i]);

//c. Demonstrate how Stack can be used to check Palindrome

void palindrome()

int i,count=0;
for(i=0; i<=(top/2); i++)

if(stack[i] == stack[top-i])

count++;

if((top/2+1)==count)

printf("\n Stack contents are Palindrome");

else

printf("\nStack contents are not palindrome");

void main()

int choice;

while(1)

printf("\n STACK OPERATIONS\n");

printf("1.Push\n 2.Pop\n 3.Display\n 4.Palindrome\n 5.Exit\n");

printf("Enter your choice\n");

scanf("%d",&choice);

switch(choice)

case 1:push();
break;

case 2:pop();

break;

case 3:display();

break;

case 4:palindrome();

break;

case 5:return;

default: printf("Invalid choice\n");

/*4.Design, Develop and Implement a Program in C for converting an Infix


Expression to Postfix Expression.

Program should support for both parenthesized and free parenthesized


expressions with the operators:

+, -, *, /, %(Remainder), ^(Power) and alphanumeric operands. */

#include<stdio.h>

void infix_to_postfix();

void push(char);

char pop();

int priority(char);
char infix[30], postfix[30],stack[30];

int top=-1;

void main()

printf("Enter the valid Infix expression \n");

scanf("%s",infix);

infix_to_postfix();

printf("\n Infix expression : %s",infix);

printf("\n Postfix expression : %s\n",postfix);

// push symbol to stack

void push(char item)

stack[++top]=item;

} // end of function push

// pop symbol from stack

char pop()

return stack[top--];

} // end of function pop


// check the priority of operator

int priority(char symb)

int p;

switch(symb)

case '+':

case '-': p=1;

break;

case '*':

case '/':

case '%': p=2;

break;

case '^':

case '$': p=3;

break;

case '(':

case ')': p=0;

break;

case '#': p=-1;

break;

} // end of switch

return p;

} // end of function priority


//converting an Infix Expression to Postfix Expression

void infix_to_postfix()

int i=0,j=0;

char symb,temp;

push('#');

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

symb=infix[i];

switch(symb)

case '(': push(symb); // push all symbols inside the ( to top of


stack

break;

case ')': temp=pop(); //pop symbol from top of stack

while(temp!='(') //pop all symbols from top of stack and store in


postfix until (

postfix[j++]=temp;

temp=pop();

} // end of while

break;

case'+':

case'-':
case'*':

case'/':

case'%':

case'^':

case'$': while(priority(stack[top])>=priority(symb)) // check for priority


of operator

temp=pop();

postfix[j++]=temp;

push(symb);

break;

default: postfix[j++]=symb;

} // end of switch

} // end of for

while(top>0) // pop remaining all symbols form top of stack and


store to postfix

temp=pop();

postfix[j++]=temp;

} // end of while

postfix[j]='\0'; // end string postfix

} // end of function infix_to_postfix


/* 5.Design, Develop and Implement a Program in C for the following Stack
Applications

a. Evaluation of postfix expression with single digit operands and operators:


+, -, *, /, %, ^

b. Solving Tower of Hanoi problem with N disks

*/

#include<stdio.h>

#include<math.h>

void push(float);

float pop();

void evaluate(char[]);

float stack[20];

int top=-1;

void main()

int choice,n;

char postfix[100];

while(1) // infinate loop for menu

printf("\n STACK APPLICATIONS");

printf("\n Enter your Choice: ");

printf("\n 1. Evaluation of postfix expression with single digit operands


and operators");
printf("\n 2. Solving Tower of Hanoi problem with N disks");

printf("\n 3. Exit \n");

scanf("%d", &choice);

switch(choice)

case 1 : printf("Enter a valid postfix expression\n");

scanf("%s",postfix);

evaluate(postfix);

break;

case 2 : printf("\n Enter the number of discs:\n");

scanf("%d",&n);

tower(n,'A','C','B');

printf("\n Total number of moves are %d",(int)pow(2,n)-1);

break;

case 3 : return;

default : printf("\n Invalid Choice");

} // end of switch

} // end of menu

} // end of main

// push item to stack

void push(float item)

stack[++top]=item;
} // end of push

// pop item from stack

float pop()

return stack[top--];

} // end of pop

// function to postfix expression with single digit operands and operators: +, -, *,


/, %, ^

void evaluate(char postfix[100])

int i;

float op1, op2, res;

char symb;

for(i=0;postfix[i]!='\0';i++) // repeate until end of string

symb=postfix[i];

if(isdigit(symb)) // check for digit or not

push(symb-'0'); // if digit push to top of stack -'0' is for ascii


to number conversion

switch(symb)

case '+':op2=pop();

op1=pop();
res=op1+op2;

push(res);

break;

case '-':op2=pop();

op1=pop();

res=op1-op2;

push(res);

break;

case '*':op2=pop();

op1=pop();

res=op1*op2;

push(res);

break;

case '/':op2=pop();

op1=pop();

if(op2==0)

printf("Division by zero Error\n");

return;

res=op1/op2;

push(res);

break;

case '%': op2=pop();


op1=pop();

if(op2==0)

printf("Division by zero Error\n");

return;

res=(int)op1%(int)op2;

push(res);

break;

case '^':op2=pop();

op1=pop();

res=pow(op1,op2);

push(res);

break;

}// end of switch

} // end of for

res=pop(); // pop the final answer from top of stack

if(top==-1)

printf("\n Result: %f\n ",res); // Display the final answer

else

printf("\nINVALID POSTFIX EXPRESSION\n");

top=-1;

}
} // end of evaluate function

// Recursive function for Solving Tower of Hanoi problem with N disks

void tower(int n,int source,int destination,int aux)

if(n==0)

return;

tower(n-1,source,aux,destination);

printf("\n Move disc %d from %c to %c",n,source,destination);

tower(n-1,aux,destination,source);

} // end of tower function

/* 6. Design, Develop and Implement a menu driven Program in C for the


following operations

on Circular QUEUE of Characters (Array Implementation of Queue with


maximum size

MAX)

a. Insert an Element on to Circular QUEUE

b. Delete an Element from Circular QUEUE

c. Demonstrate Overflow and Underflow situations on Circular QUEUE

d. Display the status of Circular QUEUE

e. Exit
Support the program with appropriate functions for each of the above operations
*/

#include<stdio.h>

#define MAX 6

int front=0,rear=0;

char q[MAX];

//a. Insert an Element on to Circular QUEUE

void insert()

char item;

if(front==(rear+1)%MAX) // Check for overflow

printf("\n Circular Queue Overflow\n");

return;

rear=(rear+1)%MAX;

printf("\n Enter the character to be inserted: ");

fflush(stdin);

scanf("%c",&item);

q[rear]=item;

} // end of insert

//b. Delete an Element from Circular QUEUE


void delete()

if(front==rear) // check for Underflow

printf("\n Circular Queue Underflow\n");

return;

front=(front+1)%MAX;

printf("\n Deleted character is: %c ",q[front]);

} // end of delete

// d. Display the status of Circular QUEUE

void display()

int i;

if(front==rear)

printf("\nCircular Queue is Empty\n");

return;

printf("\n Contents of Queue is:\n");

for(i=(front+1)%MAX; i!=rear; i=(i+1)%MAX)

printf("%c\t",q[i]);

printf("%c\t",q[i]);
} // end of display

void main()

int choice;

while(1)

printf("\n CIRCULAR QUEUE OPERATIONS");

printf("\n Enter the choice");

printf("\n 1.Insert\n 2.Delete\n 3.Display\n 4.Exit\n");

scanf("%d",&choice);

switch(choice)

case 1:

insert();

break;

case 2:delete();

break;

case 3:display();

break;

case 4:return;

default : printf("\n Invalid Choice \n");

}// end of switch

} // end of menu loop


} //end of main

/*7. Design, Develop and Implement a menu driven Program in C for the
following operations on Singly Linked List (SLL) of Student Data with the
fields: USN, Name, Branch, Sem, PhNo

a. Create a SLL of N Students Data by using front insertion.

b. Display the status of SLL and count the number of nodes in it

c. Perform Insertion / Deletion at End of SLL

d. Perform Insertion / Deletion at Front of SLL (Demonstration of stack)

e. Exit .

*/

#include<stdio.h>

#include<stdlib.h>

//NODE for singly linked list

struct node

char usn[20],name[10],branch[5];

unsigned long long int phno;

int sem;

struct node *link; // link for node of type node

};
typedef struct node * NODE;

NODE temp,FIRST=NULL;

// function to create a node

NODE getnode()

NODE x;

x=(NODE)malloc(sizeof(struct node)); //Dynamic memory allocation for


NODE

x->link=NULL; //by node default link is set to NULL to avoid dangling pointer

return x;

//Function to read linked list node information

void read()

temp=getnode();

printf("Enter USN: ");

scanf("%s",temp->usn);

printf("Enter NAME: ");

scanf("%s",temp->name);

printf("Enter Branch: ");

scanf("%s",temp->branch);

printf("Enter phone Number: ");


scanf("%llu",&temp->phno);

printf("Enter Semester: ");

scanf("%d",&temp->sem);

// Create a SLL of N Students Data by using front insertion

void create_SLL()

int n,i;

printf("Enter the number of students: ");

scanf("%d",&n);

for(i=1;i<=n;i++) // read in student details

printf("\n Enter the details of %d students\n",i);

read(); // call read() to read student details

if(FIRST==NULL) // check for empty list

FIRST=temp; // if true set new node as FIRST node of list

else{

temp->link=FIRST; // otherwise link the old node to new node

FIRST=temp; // make new node as FIRST (INSERT FRONT)

}
//Display the status of SLL and count the number of nodes in it

void display_count()

int count=1;

temp=FIRST;

printf("Student details:\n");

if(FIRST==NULL) // check for empty list

printf("Student detail is NULL and count is 0\n");

else

printf("\nUSN\tNAME\tBRANCH\tPHNO\tSEMESTER\n");

while(temp->link!=NULL) // iterate nodes of SLL until end node

count++;

printf("%s\t%s\t%s\t%llu\t%d\n",temp->usn,temp->name,temp-
>branch,temp->phno,temp->sem);

temp=temp->link; // next node

printf("%s\t%s\t%s\t%llu\t%d",temp->usn,temp->name,temp->branch,temp-
>phno,temp->sem);

printf("\n Student count is %d\n",count);

return;

}
// Perform Insertion at front of SLL

void insert_front()

printf("Enter the details of student\n");

read();

if(FIRST==NULL)

FIRST=temp;

else{

temp->link=FIRST;

FIRST=temp;

// Perform Insertion at End of SLL

NODE insert_end()

NODE last=FIRST;

printf("Enter the details of student\n");

read();

if(FIRST==NULL)

FIRST=temp;

else

while(last->link!=NULL) // find last node iteratively

last=last->link;
last->link=temp; // connect new node to last node link

return FIRST;

// Perform Deletion at front of SLL

void delete_front()

temp=FIRST;

if(FIRST==NULL) // Check for empty list

printf("List is empty\n");

else

printf("deleted element is %s\n",temp->usn);

FIRST=FIRST->link; //set 2nd node as FIRST node

free(temp); // delete previous 1st node

return;

// Perform Deletion at End of SLL

void delete_end()

NODE last=NULL;
temp=FIRST;

if(FIRST==NULL) // Check for empty list

printf("List is empty\n");

else if(FIRST->link==NULL) // // Check for single node in SLL

printf("Deleted element is %s\n",temp->usn);

free(FIRST);

FIRST=NULL;

else

while(temp->link!=NULL)

last=temp;

temp=temp->link;

last->link=NULL;

printf("Deleted element is %s\n",temp->usn);

free(temp); // delete last node

return;

}
void main()

int choice;

while(1)

printf("\n1. Create SLL\n2.Display SSL\n3.Insert front\n4.Insert end\n5.Delete


front\n6.Delete end\n7.EXIT\n");

printf("Enter your choice\n");

scanf("%d",&choice);

switch(choice)

case 1:create_SLL();

break;

case 2:display_count();

break;

case 3:insert_front();

break;

case 4:insert_end();

break;

case 5:delete_front();

break;

case 6:delete_end();

break;

case 7:return;

default:printf("\nInvalid choice\n");
}

/*8. Design, Develop and Implement a menu driven Program in C for the
following operations on Doubly Linked List (DLL) of Employee Data with the
fields: SSN, Name, Dept, Designation, Sal, PhNo

a. Create a DLL of N Employees Data by using end insertion.

b. Display the status of DLL and count the number of nodes in it

c. Perform Insertion and Deletion at End of DLL

d. Perform Insertion and Deletion at Front of DLL

e. Demonstrate how this DLL can be used as Double Ended Queue

f. Exit. */

#include<stdio.h>

struct node // structure to store employee details

char ssn[12],name[20],dept[25],desig[20];

unsigned long long int phno;

float sal;

struct node *prev;

struct node *next;

};

typedef struct node *NODE; // renaming node as NODE


NODE temp, FIRST=NULL,END=NULL;

NODE getnode() // Create node

NODE x;

x=(NODE)malloc(sizeof(struct node));

x->prev=NULL;

x->next=NULL;

return x;

void read() // read details of employee

temp=getnode();

printf("Enter SSN:");

scanf("%s",temp->ssn);

printf("Enter Name:");

scanf("%s",temp->name);

printf("Enter Dept:");

scanf("%s",temp->dept);

printf("Enter Designation:");

scanf("%s",temp->desig);

printf("Enter Phno:");
scanf("%llu",&temp->phno);

printf("Enter Salary:");

scanf("%f",&temp->sal);

return;

void Create_DLL() // Create a DLL of N Employees Data by using end


insertion.

int n,i=1;

printf("Enter the number of Employees \n");

scanf("%d",&n);

while(i<=n)

printf("Enter the details of the %d employee\n", i++);

read();

if(FIRST==NULL) // if empty list new node will be the first node

FIRST=temp;

END=temp;

else //otherwise find the last node and insert the new node

END->next=temp;

temp->prev=END;
END=temp;

} //e nd of while

} // end of create()

void display_count() //Display the status of DLL and count the number of nodes
in it

temp=FIRST;

int count=0;

if(FIRST==NULL) // check for empty list

printf("the Employee detail is NULL and count is %d\n", count);

else

printf("Employee details:\n");

printf("SSN \t EMPLOYEE NAME \t DEPARTMENT \t


DESIGNATION \t PHONE NUMBER \t SALARY");

while(temp!=NULL) // display all nodes in the list

count++;

printf("\n%s\t%s\t%s\t%s\t%llu\t%0.2f",temp->ssn, temp-
>name, temp->dept,temp->desig,temp->phno,temp->sal);

temp=temp->next;
}

printf("\n Employee count is %d\n",count);

} // end of else

return;

} // end of display()

void Insertionfront() //Perform Insertion at front of DLL

printf("Enter the details of the employee\n");

read();

if(FIRST==NULL) // if empty list new node will be the first node

FIRST=temp;

END=temp;

else // otherwise insert the new node at front

temp->next=FIRST;

FIRST->prev=temp;

FIRST=temp;

} // end of insert front

void Insertionend() //Perform Insertion at End of DLL


{

printf("Enter the details of the new employee\n");

read();

if(FIRST==NULL) // check for empty list

FIRST=temp;

END=temp;

else // otherwise find the last node and insert the new node

END->next=temp;

temp->prev=END;

END=temp;

return ;

} // end of insert end

void Deletionfront() //Delete node from front of DLL

temp=FIRST;

if(FIRST==NULL) // check for empty list

printf("List is empty\n");

else if(FIRST==END) // otherwise check for single node in list

{
printf("deleted element is %s\n", temp->ssn);

FIRST=NULL;

END=NULL;

free(temp);

else // otherwise delete node from front of DLL

printf("deleted element is %s\n", temp->ssn);

FIRST =FIRST->next;

FIRST->prev=NULL;

free(temp);

return;

} // end of deletefront

void Deletionend() // delete node at end of DLL

temp = END;

if(FIRST==NULL) // check for empty list

printf("List is empty\n");

else if(FIRST==END) // otherwise check for single node in list

printf("deleted element is %s\n", temp->ssn);

FIRST=NULL;
END=NULL;

free(temp);

else // otherwise delete end node from DLL

printf("deleted element is %s\n", temp->ssn);

END=END->prev;

END->next=NULL;

free(temp);

return ;

} // end of deletionend

void main()

int choice;

while(1)

printf(" \n 1 - Create DLL of N Employees \n 2 - Display DLL \n 3


- Insertion at front \n 4 - Insertion at end");

printf("\n 5 - Deletion at front \n 6 - Deletion at end \n 7 - Exit\n");

printf("Enter Your Choice: ");

scanf("%d",&choice);

switch(choice)

{
case 1 : Create_DLL();

break;

case 2 : display_count();

break;

case 3 : Insertionfront();

break;

case 4 : Insertionend();

break;

case 5 : Deletionfront();

break;

case 6 : Deletionend();

break;

case 7 : return;

default: printf("Invalid Choice\n");

} //end of switch

} // end of while

} // end of main

/*9. Design, Develop and Implement a Program in C for the following


operations on Singly Circular

Linked List (SCLL) with header nodes

a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-


2xyz3

b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store
the result in
POLYSUM(x,y,z)

Support the program with appropriate functions for each of the above operation
*/

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

struct node // polynomial node

int coef;

int x,y,z;

struct node *link;

};

typedef struct node *NODE;

NODE getnode() // create a node

NODE x;

x=(NODE)malloc(sizeof(struct node));

return x;

} // end of getnode

NODE readpoly()

NODE temp,head,cur;

char ch;
head=getnode(); // create a head node and set all values to -1 it is similar
to FIRST in SLL program

head->coef=-1;

head->x=-1;

head->y=-1;

head->z=-1;

head->link=head; // self reference

do

temp=getnode(); // create a polynomial node

printf("\nEnter the coefficient and exponent in decreasing


order\n");

scanf("%d%d%d%d",&temp->coef,&temp->x,&temp->y,&temp-
>z );

cur=head;

while(cur->link!=head) // find the last node

cur=cur->link;

cur->link=temp; // connect new node to the last node

temp->link=head; // point back to head

printf("\nDo you want to enter more coefficients(y/n)");

fflush(stdin); // to clear the stdin buffer

scanf("%c",&ch);

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

return head; // return the polynomial list

} // end of readpoly
int compare(NODE a,NODE b) // function to compare the A and B polynomial
nodes

if(a->x > b->x)

return 1;

else if(a->x < b->x)

return -1;

else if(a->y > b->y)

return 1;

else if(a->y < b->y)

return -1;

else if(a->z > b->z)

return 1;

else if(a->z < b->z)

return -1;

return 0;

} // end of compare

void attach(int cf,int x1,int y1, int z1, NODE *ptr) // function to attach the A
and B polynomial node to C Polynomial

NODE temp;

temp=getnode();

temp->coef=cf;
temp->x=x1;

temp->y=y1;

temp->z=z1;

(*ptr)->link=temp;

*ptr=temp;

} // end of attach

NODE addpoly(NODE a,NODE b) // function to add polynomial A and B i.e,


C=A+B

NODE starta,c ,lastc;

int sum,done=0;

starta=a;

a=a->link;

b=b->link;

c=getnode(); // create list C to store A+B

c->coef=-1;

c->x=-1;

c->y=-1;

c->z=-1;

lastc=c;

do{

switch(compare(a,b))

case -1:attach(b->coef,b->x,b->y,b->z,&lastc);
b=b->link;

break;

case 0:if(starta==a) done=1;

else{

sum=a->coef+b->coef;

if(sum)

attach(sum,a->x, a->y,a->z,&lastc);

a=a->link;b=b->link;

break;

case 1: if(starta==a) done=1;

attach(a->coef,a->x, a->y,a->z,&lastc);

a=a->link;

break;

}while(!done); // repeate until not done

lastc->link=c; // point back to head of C

return c; // return answer

void print(NODE ptr) // to print the polynomial

NODE cur;

cur=ptr->link;
while(cur!=ptr) // To print from HEAD node till END node

printf("%d*x^%d*y^%d*z^%d",cur->coef,cur->x, cur->y,
cur->z);

cur=cur->link; // move to next node

if (cur!=ptr)

printf(" + ");

} // end of print

void evaluate(NODE ptr) // function to evaluate the final polynomial

int res=0;

int x,y,z, ex,ey,ez,cof;

NODE cur;

printf("\nEnter the values of x, y,z"); // read values of X, Y and Z

scanf("%d", &x);

scanf("%d", &y);

scanf("%d", &z);

cur=ptr->link; // start with HEAD

while(cur!=ptr) // Repeat until the end of list

ex=cur->x; // exponent of x

ey=cur->y; // exponent of y

ez=cur->z; // exponent of z
cof=cur->coef; // coefficient

res+=cof*pow(x,ex)*pow(y,ey)*pow(z,ez); // compute result


for each polynomial

cur=cur->link; // move to next node

printf("\nresult: %d",res);

} // end of evaluate

void main(void)

int i, ch;

NODE a=NULL,b,c;

while(1)

printf("\n1: Represent first polynomial A");

printf("\n2: Represent Second polynomial B");

printf("\n3: Display the polynomial A");

printf("\n4: Display the polynomial B");

printf("\n5: Add A & B polynomials"); // C=A+B

printf("\n6: Evaluate polynomial C");

printf("\n7: Exit");

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

scanf("%d",&ch);

switch(ch)

{
case 1: printf("\nEnter the elements of the polynomial A");

a=readpoly();

break;

case 2:printf("\nEnter the elements of the polynomial B");

b= readpoly();

break;

case 3: print(a); // display polynomial A

break;

case 4:print(b); // display polynomial A

break;

case 5: c=addpoly(a,b); // C=A+B

printf("\nThe sum of two polynomials is: ");

print(c); // display polynomial C

printf("\n");

break;

case 6:evaluate(c); // Evaluate polynomial C

break;

case 7: return;

default: printf("\nInvalid choice!\n");

} //end of switch

} // end of while

} // end of main

10 . Design, Develop and Implement a menu driven Program in C for the


following operations on Binary Search Tree (BST) of Integers
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2

b. Traverse the BST in Inorder, Preorder and Post Order

c. Search the BST for a given element (KEY) and report the appropriate
message

e. Exit.

#include<stdio.h>

struct node // DLL node for Tree with left_link value and right_link

int value;

struct node *ltree;

struct node *rtree;

};

typedef struct node* NODE;

NODE getnode() // create a node

NODE x;

x=(NODE) malloc (sizeof(struct node));

x->ltree=NULL;

x->rtree=NULL;

return x;

} // end of getnode

NODE create(int item, NODE root) // create a BST for the given values

{
NODE temp,cur,prev;

int i , flag=0;

temp=getnode(); // create node

temp->value=item; // store value

if(root==NULL) // if empty tree then new node itself is ROOT of BST

root=temp;

return root;

else // otherwise add new node to BST

prev=NULL;

cur=root;

while (cur!=NULL) // find the leaf node

prev=cur;

if(temp->value==cur->value)

flag=1;

break;

cur=(temp->value<cur->value)?cur->ltree:cur->rtree; //
condition to choose left or right subtree

if(flag==0)
{

if(temp->value<prev->value) // if new node smaller than ROOT


then make it as left child

prev->ltree=temp;

else if(temp->value>prev->value) // otherwise if new node greater


than ROOT then make it as right child

prev->rtree=temp;

return root;

void in(NODE IN) // Recursive INORDER traversal function

if(IN!=NULL) // if tree is not empty then traverse

in(IN->ltree); // left child

printf("%d\t",IN->value); // Root

in(IN->rtree); //right child

void pre(NODE PRE) // Recursive PREORDER traversal function

{
if(PRE!=NULL) // if tree is not empty then traverse

printf("%d\t",PRE->value); // Root

pre(PRE->ltree); // left child

pre(PRE->rtree); //right child

void post(NODE POST) // Recursive POSTORDER traversal function

if(POST!=NULL) // if tree is not empty then traverse

post(POST->ltree); // left child

post(POST->rtree); //right child

printf("%d\t",POST->value); // Root

void search(NODE root) // Binary Search on BST for given Key element

int item, found=0;

NODE cur;

printf("enter the element to be searched\n");

scanf("%d",&item); // read key


if(root==NULL) // check for empty tree

printf("tree is empty\n");

return;

// for non-empty tree search for key in BST

cur=root;

while(cur!=NULL) // repeat until end

if(item==cur->value) // check key and root value is same


SUCESSFULL SEARCH

found = 1; // set flag

printf("Found key %d in tree\n",cur->value);

if(item<cur->value) // check key is greater than root value then


choose right subtree

cur=cur->ltree;

else // otherwise choose left subtree

cur=cur->rtree;

} // end of while

if(found==0) // if found flag is Zero then UNSUCESSFULL SEARCH

printf("Key not found\n");

} // end of search
void main()

int choice, item, n, i;

NODE root=NULL;

while(1)

printf("\n1. Create BST of N Integers");

printf("\n2. BST Traversal");

printf("\n3. Binary Search");

printf("\n4. Exit");

printf("\nEnter Your Choice: ");

scanf("%d",&choice);

switch(choice)

case 1: printf("\n Enter number elements : ");

scanf("%d",&n);

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

printf("Enter the item to be inserted\n");

scanf("%d",&item);

root=create(item,root);

break;
case 2: if(root==NULL) // check for empty tree

printf("Tree is empty\n");

else

{ // for non-empty tree traverse BST

printf("\n\nPREORDER traversal\n");

pre(root);

printf("\n\nINORDER traversal\n");

in(root);

printf("\n\nPOSTORDER traversal\n");

post(root);

break;

case 3: search(root);

break;

case 4: return;

default: printf("\n Invalid Choice\n");

} // end of switch

} // end of while

} // end of main

/* 11. Design, Develop and Implement a Program in C for the following


operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using
DFS/BFS method.*/

#include<stdio.h>

int a[20][20], q[20], visited[20];

int n, i, j, f=0, r=-1;

void create_graph() // Create the Digraph using Adjacency matrix

printf("\n Enter the number of cities: ");

scanf("%d",&n);

printf("\n Enter graph data in matrix form:\n");

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

for(j=1;j<=n;j++)

scanf("%d",&a[i][j]); // read adjacency matrix

return;

void bfs(int v) // Reachability using Breadth First Search

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

if(a[v][i] && !visited[i]) // check weather node is visited

q[++r]=i; // if not add it Queue

if(f<=r) // check for non empty Queue


{

visited[q[f]]=1; // set visited status for front node of Queue

bfs(q[f++]); // recursive call BSF

}// end of BSF

void main()

int v, choice;

while(1)

printf("\n1. Create a Digraph of N cities using Adjacency Matrix");

printf("\n2. Print all the nodes reachable from a given starting node in a
digraph using BFS method") ;

printf("\n3. Exit");

printf("\n Enter Your Choice: ");

scanf("%d",&choice);

switch(choice)

case 1: create_graph();

break;

case 2: printf("Enter the source vertex: ");

scanf("%d",&v);

if((v<1)||(v>n)) // check for valid source entry


printf("\nEnter a valid source vertex");

else // if valid begin test for reachability

for(i=1;i<=n;i++) // begin with assuming all cities are not visited

visited[i]=0;

visited[v]=1; // source is visited

bfs(v); // cal BFS to check reachability

printf("The reachable nodes from node %d:\n",v);

for(i=1;i<=n;i++) // display reachable cities from the source city

if(visited[i] && i !=v)

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

break;

case 3:return;

default:printf("\nInvalid Choice");

} // end of switch

} // end of while

} // end of main

/* 12. Given a File of N employee records with a set K of Keys(4-digit) which


uniquely determine the records in file F.Assume that file F is maintained in
memory by a Hash Table(HT) of m memory locations with L as the set of
memory addresses (2-digit) of locations in HT. Let the keys in K and addresses
in L are Integers.Design and develop a Program in C that uses Hash function H:
K -->L as H(K)=K mod m (remainder method),and implement hashing
technique to map a given key K to the address space L. Resolve the collision (if
any) using linear probing. */

#include <stdio.h>

#define MAX 10

void linear_prob(int a[MAX])

int flag, key, i, addrs, count;

char ans;

do

flag=0;

count=0;

printf("\n Enter 4 digit Key : ");

scanf("%4d", &key); // read a key

addrs=key%10; // generate single digit key for given key

if(a[addrs]== -1) // check for empty entry in Hash table

a[addrs] = key; // if yes the add to HT

else // if entry exits then avoid collision

printf("\nCollision Detected...!!!\n");

i=0;

while(i<MAX) // check for next available empty location in HT

if (a[i]!=-1)
count++; // count empty location in HT

i++;

} // end of while

if(count == MAX) // if HT is full then display HT and return

printf("\n Hash table is full \n");

display(a); // Display HT

return;

} // end of if

printf("\nCollision avoided successfully using LINEAR PROBING\n");

for(i=addrs+1; i<MAX; i++) // if there is empty space after key in


HT then make a entry in HT

if(a[i] == -1)

a[i] = key;

flag =1;

break;

} // end of if

i=0;

while((i<addrs) && (flag==0)) // check for empty space before key


in HT then make a entry in HT

if(a[i] == -1)

a[i] = key;
flag=1;

break;

} // end of if

i++;

} // end of while

} // end of else

printf("\n Do you wish to continue ? (y/n) ");

fflush(stdin);

scanf("%c",&ans);

} while(ans=='y' || ans == 'Y') ;// end of do while

} // end of linear probe

void display(int a[MAX]) // display the HT

int i;

printf("\n the HASH TABLE is\n Addrs \t Key");

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

printf("\n %d \t %d ", i, a[i]);

}// end of display

void main()

int a[MAX], i, choice;

for (i=0;i<MAX;i++) // initialize HT with no entries


a[i] = -1;

while(1)

printf("\n Collision handling by Linear Probing ");

printf("\n1. Insert into Hash table");

printf("\n2. Display Hash table");

printf("\n3. Exit");

printf("\n Enter your Choice : ");

scanf("%d",&choice);

switch (choice)

case 1: linear_prob(a);

break;

case 2: display(a);

break;

case 3: return;

default: printf("\n Invalid Choice");

} // end of switch

} // end of while

} // end of main

You might also like