Solution Set Data Structure Lab
Solution Set Data Structure Lab
ASSIGNMENT NO. –1
Program:
#include<stdio.h>
#include<conio.h>
void main(){
clrscr();
getch();
(2) Write a Program to read 4 data values from user without using an array or function.
Program:
#include<stdio.h>
#include<conio.h>
void main(){
string name,branch;
int batch;
float per;
clrscr();
scanf("%s",&name);
printf("Your Batch:");
scanf("%d",&batch);
printf("Your Branch:");
scanf("%s",&branch);
scanf("%f",&per);
getch();
(3) Write a Program to print table of a number entered by user without using an array
or function.
Program:
#include <stdio.h>
#include <conio.h>
void main(){
int i=1,number=0;
clrscr();
for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}
getch();
}
(4) Write a Program to read 10 different data values one by one using a variable .If
entered value is odd then add it to addsum else add it to evensum and then display
addsum and evensum.
Program:
#include <stdio.h>
#include <conio.h>
void main(){
int a,evensum=0,oddsum=0;
clrscr();
int check(int a)
{
int b= a;
if(a%2==0)
return 0;
else
return 1;
}
for (i=1;i<=10;i++){
(5) Write a Program to read 3 data values from user and add first two data values.
After that subtract result from the 3 rd data value. If the final result negative then
display message “ Result –ve” else display “Result +ve”.
Program:
#include <stdio.h>
#include <conio.h>
void main(){
int a,b,c;
clrscr();
if ( check(a,b,c)==0)
{
printf(“The result is –ve”);
else
printf(“The result is +ve”);
for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}
getch();
}
(6) Write a Program to implement Reference operator(&) and Dereference operator(*) for
pointer.
Program:
#include <stdio.h>
int main(){
int* pc;
int c;
c=22;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
c=11;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
return 0;
(7) Write a Program to using pointer by “call by value” and “call by reference” method
Program1:Call by value in C
#include <stdio.h>
#include <conio.h>
num=num+100;
int main(){
int x=100;
clrscr();
getch();
return 0;
Program2:Call by reference in C
#include <stdio.h>
#include <conio.h>
(*num) += 100;
int main() {
int x=100;
clrscr();
getch();
return 0;
(8) Write a Program to Store Information(name, roll and marks) of a Student Using
Structure.
Program:
#include <stdio.h>
struct student
char name[50];
int roll;
float marks;
} s;
int main()
printf("Enter information:\n");
scanf("%d", &s.roll);
scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: ");
puts(s.name);
return 0;
ASSIGNMENT NO. –2
void main()
{
int array[10];
int i, j, n, m, temp, key, pos;
int main()
{
int array[100], position, c, n;
else
{
for ( c = position - 1 ; c < n - 1 ; c++ )
array[c] = array[c+1];
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
/* for loop for receiving inputs from user and storing it in array*/
for (x=0; x<=5;x++)
{
printf("enter the integer number %d\n", x);
scanf("%d", &num[x]);
}
for (x=0; x<=19;x++)
{
sum = sum+num[x];
}
avg = sum/20;
printf("%d", avg);
return 0;
}
#include <stdio.h>
void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int
rowSecond, int columnSecond);
int main()
{
int firstMatrix[10][10], secondMatrix[10][10], mult[10][10], rowFirst, columnFirst,
rowSecond, columnSecond, i, j, k;
// If colum of first matrix in not equal to row of second matrix, asking user to enter the
size of matrix again.
while (columnFirst != rowSecond)
{
printf("Error! column of first matrix not equal to row of second.\n");
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &rowFirst, &columnFirst);
printf("Enter rows and column for second matrix: ");
scanf("%d%d", &rowSecond, &columnSecond);
}
return 0;
}
void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int
rowSecond, int columnSecond)
{
int i, j;
printf("\nEnter elements of matrix 1:\n");
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnFirst; ++j)
{
printf("Enter elements a%d%d: ", i + 1, j + 1);
scanf("%d", &firstMatrix[i][j]);
}
}
(5).Write A Program to find the diagonal elements of the 2-D array, also find the sum of
diagonal elements.
Solution:
#include<stdio.h>
void main()
{
int a[20][20],b[20][20],c[20][20],i,j,m,n;
printf("enter the rows and columns of the matrixs\n");
scanf("%d%d",&m,&n);
printf("Enter the first matrics\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]); //reads the matrics
}
}
printf("The diagonal element of the matrics are\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
printf("%d ,",a[i][j]); //prints the diagonal element of the matrics
}
}
}
#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
return 0;
}
#include <stdio.h>
void main()
{
int array1[50], array2[50], array3[100], m, n, i, j, k = 0;
#include <stdio.h>
main ()
{
char name[39+1];
printf("Enter your college name name :");
scanf("%s", name);
printf("Hello %s", name);
}
ASSIGNMENT NO. –3
(1) Write a function to create and display the linear linked list.
Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
};
printf(" ]");
}
link->key = key;
link->data = data;
int length() {
int length = 0;
struct node *current;
return length;
}
return current;
}
void sort() {
tempKey = current->key;
current->key = next->key;
next->key = tempKey;
}
current = current->next;
next = next->next;
}
}
}
*head_ref = prev;
}
main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
//print list
printList();
while(!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
delete(4);
printf("List after deleting an item: ");
printList();
printf("\n");
foundLink = find(4);
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
printf("\n");
sort();
reverse(&head);
printf("\nList after reversing the data: ");
printList();
}
(2) Write functions to implement the insertion and deletion operation of linear linked
list .
Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
};
printf(" ]");
}
link->key = key;
link->data = data;
int length() {
int length = 0;
struct node *current;
return length;
}
return current;
}
void sort() {
tempKey = current->key;
current->key = next->key;
next->key = tempKey;
}
current = current->next;
next = next->next;
}
}
}
*head_ref = prev;
}
main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
//print list
printList();
while(!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
delete(4);
printf("List after deleting an item: ");
printList();
printf("\n");
foundLink = find(4);
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
printf("\n");
sort();
reverse(&head);
printf("\nList after reversing the data: ");
printList();
}
(3) Write function to implement the concatenation operation of linear linked list.
Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
};
printf(" ]");
}
link->key = key;
link->data = data;
int length() {
int length = 0;
struct node *current;
return length;
}
return current;
}
void sort() {
tempKey = current->key;
current->key = next->key;
next->key = tempKey;
}
current = current->next;
next = next->next;
}
}
}
*head_ref = prev;
}
void main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
//print list
printList();
while(!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
delete(4);
printf("List after deleting an item: ");
printList();
printf("\n");
foundLink = find(4);
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
printf("\n");
sort();
reverse(&head);
printf("\nList after reversing the data: ");
printList();
}
(4) Write function to implement the polynomial addition with the help of linear linked
list.
Program:
#include<stdio.h>
#include<stdlib.h>
struct pNode {
int coeff, exp;
struct pNode *next;
};
/*
* creates new Node and fill the given data
*/
struct pNode * createNode(int coeff, int exp) {
struct pNode *ptr;
ptr = (struct pNode *) malloc(sizeof (struct pNode));
ptr->coeff = coeff;
ptr->exp = exp;
ptr->next = NULL;
return ptr;
}
/* Adding poly nomial n2 and n3 and the output will be stroed in n1 list */
void polynomial_add(struct pNode **n1, struct pNode *n2, struct pNode *n3) {
struct pNode * temp;
/*
* if some nodes in input list (n2) left remain, then add those
* nodes to the output list (n3).
*/
while (n2) {
if (*n1 == NULL) {
*n1 = (struct pNode *) malloc(sizeof (struct pNode));
temp = *n1;
} else {
temp->next = (struct pNode *) malloc(sizeof (struct pNode));
temp = temp->next;
}
temp->coeff = n2->coeff;
temp->exp = n2->exp;
n2 = n2->next;
}
/*
* if some nodes in the input list (n3) left remain, then add those
* nodes to the output list n3.
*/
while (n3) {
if (*n1 == NULL) {
*n1 = (struct pNode *) malloc(sizeof (struct pNode));
temp = *n1;
} else {
temp->next = (struct pNode *) malloc(sizeof (struct pNode));
temp = temp->next;
}
temp->coeff = n2->coeff;
temp->exp = n2->exp;
n3 = n3->next;
}
return;
}
/* traverse the given input list and print the data in each node */
void walkPolyList(struct pNode *ptr) {
int i = 0;
while (ptr) {
printf("%dX^%d %c ", ptr->coeff, ptr->exp, ptr->next?'+':'\0');
ptr = ptr->next;
i++;
}
printf("\n");
return;
}
walkPolyList(head1);
walkPolyList(head2);
polynomial_add(&head3, head1, head2);
walkPolyList(head3);
head1 = deletePolyList(head1);
head2 = deletePolyList(head2);
head3 = deletePolyList(head3);
return 0;
}
(5) Write function to insert a data value after given data value in linear/single linked
list.
Program:
#include<stdio.h>
#include<conio.h>
//Create a basic structure for NODE from which new nodes can be created.
struct node
{
int data;
struct node *link;
};
void main()
{
int choice;
int cont = 1;
clrscr();
while(cont == 1)
{
//Display menu to the user
printf("\n1. Insert at front\n");
printf("\n2. Insert at end\n");
printf("\n3. Insert at any position\n");
printf("\n4. Display linked list\n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert_front();
break;
case 2:
insert_end();
break;
case 3:
insert_any();
break;
case 4:
display();
break;
}
getch();
}
temp->data = data_value;
temp->link = header->link;
header->link = temp;
}
temp->data = data_value;
temp->link = ptr->link;
ptr->link = temp;
}
(6) Write function to insert a data value after given no. of node in linear/single linked
list.
Program:
#include<stdio.h>
#include<conio.h>
//Create a basic structure for NODE from which new nodes can be created.
struct node
{
int data;
struct node *link;
};
clrscr();
while(cont == 1)
{
//Display menu to the user
printf("\n1. Insert at front\n");
printf("\n2. Insert at end\n");
printf("\n3. Insert at any position\n");
printf("\n4. Display linked list\n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert_front();
break;
case 2:
insert_end();
break;
case 3:
insert_any();
break;
case 4:
display();
break;
}
getch();
}
temp->data = data_value;
temp->link = header->link;
header->link = temp;
}
temp->data = data_value;
temp->link = ptr->link;
ptr->link = temp;
}
ASSIGNMENT NO. –4
(1) Write a program to create and display the Circular linked list.
Program:
#include<stdio.h>
#include<conio.h>
struct circular
{
int i;
struct circular *next;
};
int cnt=0;
void create(void);
void insert(void);
void display(void);
void del(void);
void main()
{
int ch=0;
clrscr();
while(ch!=5)
{
printf("\n1.CREATE");
printf("\n2.INSERT");
printf("\n3.DELETE");
printf("\n4.DISPLAY");
printf("\n5.EXIT");
scanf("%d",&ch);
if(ch==1)
{
create();
cnt++;
cnt++;
}
if(ch==2)
{
insert();
cnt++;
}
if(ch==3)
{
del();
cnt--;
}
if(ch==4)
{
display();
}
if(ch==5)
{
break;
}
}
getch();
}
void create()
{
head=(struct circular *)malloc(sizeof(struct circular));
head->next=head;
printf("ENETER THE DATA");
scanf("%d",&head->i);
temp=head;
}
void insert()
{
int add,t;
void display()
{
p=head;
printf("%d-->",p->i);
p=p->next;
while(p!=head)
{
printf("%d-->",p->i);
p=p->next;
}
}
void del(void)
{
int add,t;
(2) Write a program to implement delete and display operation of Circular linked list.
Program:
#include<stdio.h>
#include<conio.h>
struct circular
{
int i;
struct circular *next;
};
void create(void);
void insert(void);
void display(void);
void del(void);
void main()
{
int ch=0;
clrscr();
while(ch!=5)
{
printf("\n1.CREATE");
printf("\n2.INSERT");
printf("\n3.DELETE");
printf("\n4.DISPLAY");
printf("\n5.EXIT");
scanf("%d",&ch);
if(ch==1)
{
create();
cnt++;
cnt++;
}
if(ch==2)
{
insert();
cnt++;
}
if(ch==3)
{
del();
cnt--;
}
if(ch==4)
{
display();
}
if(ch==5)
{
break;
}
}
getch();
}
void create()
{
head=(struct circular *)malloc(sizeof(struct circular));
head->next=head;
printf("ENETER THE DATA");
scanf("%d",&head->i);
temp=head;
}
void insert()
{
int add,t;
void display()
{
p=head;
printf("%d-->",p->i);
p=p->next;
while(p!=head)
{
printf("%d-->",p->i);
p=p->next;
}
}
void del(void)
{
int add,t;
(3) Write a program to display all the data values starting from 3rd node in the circular
linked list.
Program:
void display()
{
struct circular *q;
p=head;
p=p->next;
p=p->next;
q=p;
printf("%d-->",p->i);
while(p!=q)
{
printf("%d-->",p->i);
p=p->next;
}
}
(4) Write a program to delete first node of the circular linked list.
Program:
#include<stdio.h>
#include<conio.h>
struct circular
{
int i;
struct circular *next;
};
void main()
{
int ch=0;
clrscr();
while(ch!=5)
{
printf("\n1.CREATE");
printf("\n2.INSERT");
printf("\n3.DELETE");
printf("\n4.DISPLAY");
printf("\n5.EXIT");
scanf("%d",&ch);
if(ch==1)
{
create();
cnt++;
cnt++;
}
if(ch==2)
{
insert();
cnt++;
}
if(ch==3)
{
del();
cnt--;
}
if(ch==4)
{
display();
}
if(ch==5)
{
break;
}
}
getch();
}
void create()
{
head=(struct circular *)malloc(sizeof(struct circular));
head->next=head;
printf("ENETER THE DATA");
scanf("%d",&head->i);
temp=head;
}
void insert()
{
int add,t;
void display()
{
p=head;
printf("%d-->",p->i);
p=p->next;
while(p!=head)
{
printf("%d-->",p->i);
p=p->next;
}
}
void del(void)
{
int add,t;
ASSIGNMENT NO. –5
(1) Write functions to create and display the double linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
void createList(int n);
void displayListFromFirst();
void displayListFromEnd();
int main()
{
int n, choice;
head = NULL;
last = NULL;
printf("Enter the number of nodes you want to create: ");
scanf("%d", &n);
createList(n); //Creates list of n nodes
printf("\nPress 1 to display list from First");
printf("\nPress 2 to display list from End : ");
scanf("%d", &choice);
if(choice==1)
{
displayListFromFirst();
}
else if(choice == 2)
{
displayListFromEnd();
}
return 0;
}
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
head = (struct node *)malloc(sizeof(struct node));
if(head != NULL)
{
printf("Enter data of 1 node: ");
scanf("%d", &data);
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
if(newNode != NULL)
{
printf("Enter data of %d node: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->prev = last; //Links new node with the previous node
newNode->next = NULL;
void displayListFromFirst()
{
struct node * temp;
int n = 1;
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
printf("\n\nDATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
void displayListFromEnd()
{
struct node * temp;
int n = 0;
if(last == NULL)
{
printf("List is empty.");
}
else
{
temp = last;
printf("\n\nDATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of last-%d node = %d\n", n, temp->data);
n++;
(2) Write functions to implement the insertion and deletion operation of double linked
list.
Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
struct node *prev;
};
int length() {
int length = 0;
struct node *current;
return length;
}
while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
printf(" ]");
}
while(ptr != NULL) {
//print data
printf("(%d,%d) ",ptr->key,ptr->data);
printf(" ]");
}
if(isEmpty()) {
//make it the last link
last = link;
} else {
//update first prev link
head->prev = link;
}
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()) {
//make it the last link
last = link;
} else {
//make link a new last link
last->next = link;
head = head->next;
//return the deleted link
return tempLink;
}
last = last->prev;
if(current->next == NULL) {
return NULL;
} else {
//store reference to current link
previous = current;
if(current == last) {
//change last to point to prev link
last = current->prev;
} else {
current->next->prev = current->prev;
}
return current;
}
//create a link
struct node *newLink = (struct node*) malloc(sizeof(struct node));
newLink->key = key;
newLink->data = data;
if(current == last) {
newLink->next = NULL;
last = newLink;
} else {
newLink->next = current->next;
current->next->prev = newLink;
}
newLink->prev = current;
current->next = newLink;
return true;
}
main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("\n");
printf("\nList (Last to first): ");
displayBackward();
(3) Write function to display data values in reverse order using double linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
int main()
{
int n, data, choice=1;
head = NULL;
last = NULL;
while(choice != 0)
{
printf("============================================\n");
printf("DOUBLY LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Reverse List\n");
printf("3. Display list\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
reverseList();
break;
case 3:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-3");
}
printf("\n\n\n\n\n");
}
return 0;
}
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
head = (struct node *)malloc(sizeof(struct node));
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
newNode->data = data;
newNode->prev = last; //Links new node with the previous node
newNode->next = NULL;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
/**
* Reverses the order of the doubly linked list
*/
void reverseList()
{
struct node *current, *temp;
current = head;
while(current != NULL)
{
/*
* Swap the previous and next address fields of current node
*/
temp = current->next;
current->next = current->prev;
current->prev = temp;
/*
* Swap the head and last pointers
*/
temp = head;
head = last;
last = temp;
(4) Write function to insert a data value after given data value in double linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
/*
* Functions used in this program
*/
void createList(int n);
void displayList();
void insertAtBeginning(int data);
void insertAtEnd(int data);
void insertAtN(int data, int position);
int main()
{
int n, data, choice=1;
head = NULL;
last = NULL;
/*
* Runs forever until user chooses 0
*/
while(choice != 0)
{
/*
* Menu creation to use the program
*/
printf("============================================\n");
printf("DOUBLY LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Insert node - at beginning\n");
printf("3. Insert node - at end\n");
printf("4. Insert node - at N\n");
printf("5. Display list\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");
scanf("%d", &choice);
/*
* Chooses from different menu operation
*/
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
printf("Enter data of first node : ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 3:
printf("Enter data of last node : ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 4:
printf("Enter the position where you want to insert new node: ");
scanf("%d", &n);
printf("Enter data of %d node : ", n);
scanf("%d", &data);
insertAtN(data, n);
break;
case 5:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-5");
}
printf("\n\n\n\n\n");
}
return 0;
}
/**
* Creates a doubly linked list of n nodes.
*
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
/*
* Creates and links the head node
*/
head = (struct node *)malloc(sizeof(struct node));
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
/*
* Creates and links rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->prev = last; //Links new node with the previous node
newNode->next = NULL;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
if(head == NULL)
{
printf("Error, List is Empty!\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head; //Points to next node which is currently head
newNode->prev = NULL; //Previous node of first node is NULL
/**
* Inserts a new node at the end of the doubly linked list
*
* @data Data of the last node i.e data of the new node
*/
void insertAtEnd(int data)
{
struct node * newNode;
if(last == NULL)
{
printf("Error, List is empty!\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
newNode->prev = last;
last->next = newNode;
last = newNode;
if(head == NULL)
{
printf("Error, List is empty!\n");
}
else
{
temp = head;
i=1;
if(position == 1)
{
insertAtBeginning(data);
}
else if(temp == last)
{
insertAtEnd(data);
}
else if(temp!=NULL)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = temp->next; //Connects new node with n+1th node
newNode->prev = temp; //Connects new node with n-1th node
if(temp->next != NULL)
{
/* Connects n+1th node with new node */
temp->next->prev = newNode;
}
/* Connects n-1th node with new node */
temp->next = newNode;
(5) Write function to insert a data value after given no. of node in double linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
/*
* Functions used in this program
*/
void createList(int n);
void displayList();
void insertAtBeginning(int data);
void insertAtEnd(int data);
void insertAtN(int data, int position);
int main()
{
int n, data, choice=1;
head = NULL;
last = NULL;
/*
* Runs forever until user chooses 0
*/
while(choice != 0)
{
/*
* Menu creation to use the program
*/
printf("============================================\n");
printf("DOUBLY LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Insert node - at beginning\n");
printf("3. Insert node - at end\n");
printf("4. Insert node - at N\n");
printf("5. Display list\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");
scanf("%d", &choice);
/*
* Chooses from different menu operation
*/
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
printf("Enter data of first node : ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 3:
printf("Enter data of last node : ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 4:
printf("Enter the position where you want to insert new node: ");
scanf("%d", &n);
printf("Enter data of %d node : ", n);
scanf("%d", &data);
insertAtN(data, n);
break;
case 5:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-5");
}
printf("\n\n\n\n\n");
}
return 0;
}
/**
* Creates a doubly linked list of n nodes.
*
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
/*
* Creates and links the head node
*/
head = (struct node *)malloc(sizeof(struct node));
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
/*
* Creates and links rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->prev = last; //Links new node with the previous node
newNode->next = NULL;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
if(head == NULL)
{
printf("Error, List is Empty!\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head; //Points to next node which is currently head
newNode->prev = NULL; //Previous node of first node is NULL
newNode->data = data;
newNode->next = NULL;
newNode->prev = last;
last->next = newNode;
last = newNode;
/**
* Inserts a node at any position in the doubly linked list
* @data Data of the new node to be inserted
* @position Position where to insert the new node
*/
void insertAtN(int data, int position)
{
int i;
struct node * newNode, *temp;
if(head == NULL)
{
printf("Error, List is empty!\n");
}
else
{
temp = head;
i=1;
if(position == 1)
{
insertAtBeginning(data);
}
else if(temp == last)
{
insertAtEnd(data);
}
else if(temp!=NULL)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = temp->next; //Connects new node with n+1th node
newNode->prev = temp; //Connects new node with n-1th node
if(temp->next != NULL)
{
/* Connects n+1th node with new node */
temp->next->prev = newNode;
}
/* Connects n-1th node with new node */
temp->next = newNode;
(6) Write a program to create and display the Circular double linked list.
Program:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
int data;
struct DCLL
{
int info;
struct DCLL *rptr, *lptr;
}*start = NULL, *temp, *neww, *prev, *end = NULL;
void ins_beg_dcll();
void ins_end_dcll();
void del_beg_dcll();
void del_end_dcll();
void create_dcll();
void travers();
void insert();
void delet();
void search();
void update();
void main()
{
int choice;
char ch, ch2 = 'y';
do
{
if (start == NULL)
{
do
{
clrscr();
printf("\n\nError : Linked LIst is Empty Want to Create (Y/N).. ");
fflush(stdin);
scanf("%c", &ch);
if (ch == 'n' || ch == 'N')
{
exit();
}
else if (ch == 'y' || ch == 'Y')
{
create_dcll();
break;
}
else
{
printf("\n\nError : Invalid Choice");
}
} while (ch == 'y' || ch == 'Y');
}
else
{
clrscr();
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Traverse");
printf("\n4. Search");
printf("\n5. Update");
printf("\n\nPress 0 to Exit");
switch (choice)
{
case 0:
exit();
break;
case 1:
insert();
travers();
break;
case 2:
delet();
travers();
break;
case 3:
travers();
break;
case 4:
search();
break;
case 5:
update();
break;
default:
printf("\n\nError : Invalid Choice. \n");
}
printf("\n\nWant to Continue (Y/N)... ");
fflush(stdin);
scanf("%c", &ch2);
}
temp->info = data;
temp->rptr = start;
temp->lptr = start;
if (start == NULL)
{
start = temp;
end = temp;
start->rptr = start;
start->lptr = start;
}
else
{
temp->lptr = end;
end->rptr = temp;
temp->rptr = start;
start->lptr = temp;
end = temp;
}
if (pos == 1)
{
ins_beg_dcll();
}
else
{
while (count != pos - 1 && temp->rptr != start)
{
count++;
temp = temp->rptr;
}
if (temp->rptr == start && count < pos - 1)
{
printf("\n\nError : Invalid Position...");
}
else if (temp->rptr == start && count == pos - 1)
{
ins_end_dcll();
}
else
{
neww->rptr = temp->rptr;
neww->lptr = temp;
temp->rptr->lptr = neww;
temp->rptr = neww;
}
}
}
void delet()
{
int pos, count = 1;
printf("\n\nEnter Position : ");
scanf("%d", &pos);
temp = start;
if (pos == 1)
{
del_beg_dcll();
}
else
{
while (count != pos && temp != end)
{
prev = temp;
temp = temp->rptr;
count++;
}
if (temp == start)
{
printf("\n\nError : Search value doesn't exists.");
}
}
void update()
{
int pos, count = 1, dt;
printf("\n\nEnter Position : ");
scanf("%d", &pos);
printf("\nEnter New Info : ");
scanf("%d", &dt);
if (temp == start)
{
printf("\n\nError : Invalid Choice ");
}
}
ASSIGNMENT NO. –6
Program:
/*PUSH FUNCTION*/
void push (int stack[], int item)
{ if (top == (MAX-1))
status = 0;
else
{ status = 1;
++top;
stack [top] = item;
}
}
2. Write a function to implement the pop operation in stack with the help of static
memory
allocation .
Program:
/*POP FUNCTION*/
int pop (int stack[])
{
int ret;
if (top == -1)
{ ret = 0;
status = 0;
}
else
{ status = 1;
ret = stack [top];
--top;
}
return ret;
}
3. Write a function to implement the peek operation in stack with the help of static
memory allocation.
Program:
//Peek operation..................
void peek()
{
if(top==-1)
{
printf("stack is under flow");
}
else
{
Note: A complete c program for PUSH, POP and PEEK operation in stack with the
help of static memory allocation(i.e. Array).
Program:
#include<stdio.h>
#define MAX 50
void push();
void pop();
void peep();
void display();
int a[MAX],top = -1,item,i;
int main()
{
int n;
do
{
printf("\n\n\nwhat u want to do \n\n1. for push \n\n2. for pop \n\n3.for peek \n\n4. for
display \n\n5.for exit\n\n ");
scanf("%d",&n);
switch(n)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
default :
printf("invalid no");
}
}while(n!=5);
}
//Push operation................................
void push()
{
if(top==MAX-1)
{
printf("stack is over flow");
}
else
{
printf("entet the item");
scanf("%d",&item);
top++;
a[top]=item;
printf("\n\n\ninsreted item is %d",item);
}
}
// Pop Opretion........................
void pop()
{
if(top==-1)
{
printf("stack is under flow");
}
else
{
item=a[top];
top--;
printf("\n\n deleted item is %d",item);
}
}
//Peek operation..................
void peek()
{
if(top==-1)
{
printf("stack is under flow");
}
else
{
printf("\n\n top is on %d",a[top]);
}
}
void display()
{
if(top == -1)
{
printf("stack is Empty");
}
else
{
for(i=0; i<=top; i++)
{
printf("\n\n stack is %d",a[i]);
}
}
}
4. Write a function to implement the push operation in stack with the help of dynamic
memory allocation.
Program:
void push()
{
int val,count;
count = st_count();
{
printf("\nEnter value which you want to push into the stack :\n");
scanf("%d",&val);
temp->data = val;
temp->link = top;
top = temp;
}
else
printf("WARNING: STACK FULL\n");
}
5. Write a function to implement the pop operation stack with the help of dynamic
memory allocation.
Program:
{
temp = top;
printf("Value popped out is %d \n",temp->data);
top = top->link;
free(temp);
}
}
6. Write a function to implement the peek operation stack with the help of dynamic
memory allocation.
Program:
int peek()
{
if(isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
return top->data;
}
Note: A complete c program for PUSH, POP and PEEK operation in stack with the
help of dynamic memory allocation (i.e. using malloc function).
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
}*top = NULL;
int isEmpty()
{
if(top == NULL)
{
return 1;
}
else
{
return 0;
}
}
int delete_node()
{
struct node *temp;
int item;
if(isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
temp = top;
item = temp->data;
top = top->link;
free(temp);
return item;
}
void display()
{
struct node *ptr;
if(isEmpty())
{
printf("Stack is Empty\n");
return;
}
printf("Stack Elements:\n\n");
for(ptr = top; ptr != NULL; ptr = ptr->link)
{
printf(" %d\n", ptr->data);
}
printf("\n");
}
int peek()
{
if(isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
return top->data;
}
int main()
{
int option, element;
while(1)
{
printf("1. Push an Element on the Stack\n");
printf("2. delete_node or Delete an Element from the Stack\n");
printf("3. Display Top-most item (Peek) of the Stack\n");
printf("4. Display All Element of the Stack\n");
printf("5. Exit\n");
printf("Enter your Option:\t");
scanf("%d", &option);
switch(option)
{
case 1:
printf("Enter the item to be Pushed on the Stack:\t");
scanf("%d", &element);
push(element);
break;
case 2:
element = delete_node();
printf("Deleted Element:\t%d\n", element);
break;
case 3:
printf("Element at the Top of Stack:\t%d\n", peek());
break;
case 4:
display();
break;
case 5:
exit(1);
default :
printf("Wrong Option Selected\n");
}
}
return 0;
}
Program:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,top1,top2,ch=1,a,i,arr[100];
printf("Enter size of array you want to use\n");
scanf("%d",&n);
top1=-1;
top2=n;
while(ch!=0)
{
printf("What do u want to do?\n");
printf("1.Push element in stack 1\n");
printf("2.Push element in stack 2\n");
printf("3.Pop element from stack 1\n");
printf("4.Pop element from stack 2\n");
printf("5.Display stack 1\n");
printf("6.Display stack 2\n");
printf("0.EXIT\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
printf("Enter the element\n");
scanf("%d",&a);
if(top1!=(top2-1))
arr[++top1]=a;
else
printf("Overflow\n");
break;
}
case 2:
{
printf("Enter the element\n");
scanf("%d",&a);
if(top2!=(top1+1))
arr[--top2]=a;
else
printf("Overflow\n");
break;
}
case 3:
{
if(top1==-1)
printf("Stack1 is empty\n");
else
{
a=arr[top1--];
printf("%d\n",a);
}
break;
}
case 4:
{
if(top2==n)
printf("Stack2 is empty\n");
else
{
a=arr[top2++];
printf("%d\n",a);
}
break;
}
case 5:
{
if(top1==-1)
printf("Stack1 is empty\n");
else
{
printf("Stack1 is-->>\n");
for(i=0;i<=top1;i++)
printf("%d ",arr[i]);
printf("\n");
}
break;
}
case 6:
{
if(top2==n)
printf("Stack2 is empty\n");
else
{
printf("Stack2 is-->>\n");
for(i=(n-1);i>=top2;i--)
printf("%d ",arr[i]);
printf("\n");
}
break;
}
case 0:
break;
}
}
}
ASSIGNMENT NO. –7
(1)Write a function to implement insertion in a linear queue with the help of static
memory allocation.
Program:
insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*End of insert()*/
(2) Write a function to implement deletion in a linear queue with the help of static
memory allocation.
Program:
delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /*End of delete() */
Note: A complete c program for insertion, deletion operation in linear queue with the
help of static memory allocation.
Program:
#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
default:
printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
} /*End of main()*/
insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*End of insert()*/
delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /*End of delete() */
display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /*End of display() */
(3) Write a function to implement insertion in a linear queue with the help of dynamic
memory allocation.
Program:
Program:
Note: A complete c program for insertion, deletion operation in linear queue with the
help of dynamic memory allocation.
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct node
{
int data;
struct node *link;
}*front, *rear;
// function protypes
void insert();
void delete();
void queue_size();
void check();
void first_element();
void main()
{
int choice, value;
while(1)
{
printf("enter the choice \n");
printf("1 : create an empty queue \n2 : Insert element\n");
printf("3 : Dequeue an element \n4 : Check if empty\n");
printf("5. Get the first element of the queue\n");
printf("6. Get the number of entries in the queue\n");
printf("7. Exit\n");
scanf("%d", &choice);
switch (choice) // menu driven program
{
case 1:
printf("Empty queue is created with a capacity of %d\n", MAX);
break;
case 2:
insert();
break;
case 3:
delete();
break;
case 4:
check();
break;
case 5:
first_element();
break;
case 6:
queue_size();
break;
case 7:
exit(0);
default:
printf("wrong choice\n");
break;
}
}
}
(5) Write a functions to implement the insertion and deletion operations on a circular
queue with the help of static memory allocation.
Program:
#include<stdio.h>
#define SIZE 5 /* Size of Circular Queue */
int CQ[SIZE],f=-1,r=-1; /* Global declarations */
CQinsert(int elem)
{ /* Function for Insert operation */
if( CQfull()) printf("\n\n Overflow!!!!\n\n");
else
{
if(f==-1)f=0;
r=(r+1) % SIZE;
CQ[r]=elem;
}
}
int CQdelete()
{ /* Function for Delete operation */
int elem;
if(CQempty()){ printf("\n\nUnderflow!!!!\n\n");
return(-1); }
else
{
elem=CQ[f];
if(f==r){ f=-1; r=-1;} /* Q has only one element ? */
else
f=(f+1) % SIZE;
return(elem);
}
}
int CQfull()
{ /* Function to Check Circular Queue Full */
if( (f==r+1) || (f == 0 && r== SIZE-1)) return 1;
return 0;
}
int CQempty()
{ /* Function to Check Circular Queue Empty */
if(f== -1) return 1;
return 0;
}
display()
{ /* Function to display status of Circular Queue */
int i;
if(CQempty()) printf(" \n Empty Queue\n");
else
{
printf("Front[%d]->",f);
for(i=f;i!=r;i=(i+1)%SIZE)
printf("%d ",CQ[i]);
printf("%d ",CQ[i]);
printf("<-[%d]Rear",r);
}
}
main()
{ /* Main Program */
int opn,elem;
do
{
}while(opn != 4);}
ASSIGNMENT NO. –8
OBJECTIVE :- Implement the following programs with the help of Binary Tree.
#include<stdio.h>
#include<malloc.h>
struct binNode
{
int val;
struct binNode *left,*right;
};
struct binNode *createbinTree();
struct binNode *attach(struct binNode *tree, struct binNode *node);
void inOrderTravel(struct binNode *binTree);
void main()
{
struct binNode *binTree;
binTree=createbinTree();
printf("The tree is:");
inOrderTravel(binTree);
}
struct binNode *createbinTree()
{
int val,size;
struct binNode *treePtr,*newNode;
treePtr=NULL;
val=0;
size=sizeof(struct binNode);
while(val>=0)
{
printf("\nEnter the val");
scanf("%d",&val);
if (val>=0)
{
newNode=(struct binNode *) malloc (size );
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
treePtr=attach(treePtr,newNode);
}
}
return treePtr;
}
struct binNode *attach(struct binNode *tree,struct binNode *node)
{
if (tree==NULL)
tree=node;
else
{
if (node->val<tree->val)
tree->left=attach(tree->left,node);
else
tree->right=attach(tree->right,node);
}
return tree;
}
void inOrderTravel(struct binNode *binTree)
{
if( binTree==NULL)
return ;
inOrderTravel(binTree->left);
printf("%d-",binTree->val);
inOrderTravel(binTree->right);
}
#include<stdio.h>
#include<malloc.h>
struct binNode
{
int val;
struct binNode *left,*right;
};
struct binNode *createbinTree();
struct binNode *attach(struct binNode *tree, struct binNode *node);
void inOrderTravel(struct binNode *binTree);
void main()
{
struct binNode *binTree;
binTree=createbinTree();
printf("The tree is:");
inOrderTravel(binTree);
}
struct binNode *createbinTree()
{
int val,size;
struct binNode *treePtr,*newNode;
treePtr=NULL;
val=0;
size=sizeof(struct binNode);
while(val>=0)
{
printf("\nEnter the val");
scanf("%d",&val);
if (val>=0)
{
newNode=(struct binNode *) malloc (size );
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
treePtr=attach(treePtr,newNode);
}
}
return treePtr;
}
struct binNode *attach(struct binNode *tree,struct binNode *node)
{
if (tree==NULL)
tree=node;
else
{
if (node->val<tree->val)
tree->left=attach(tree->left,node);
else
tree->right=attach(tree->right,node);
}
return tree;
}
void inOrderTravel(struct binNode *binTree)
{
if( binTree==NULL)
return ;
printf("%d-",binTree->val);
inOrderTravel(binTree->left);
inOrderTravel(binTree->right);
}
#include<stdio.h>
#include<malloc.h>
struct binNode
{
int val;
struct binNode *left,*right;
};
struct binNode *createbinTree();
struct binNode *attach(struct binNode *tree, struct binNode *node);
void inOrderTravel(struct binNode *binTree);
void main()
{
struct binNode *binTree;
binTree=createbinTree();
printf("The tree is:");
inOrderTravel(binTree);
}
struct binNode *createbinTree()
{
int val,size;
struct binNode *treePtr,*newNode;
treePtr=NULL;
val=0;
size=sizeof(struct binNode);
while(val>=0)
{
printf("\nEnter the val");
scanf("%d",&val);
if (val>=0)
{
newNode=(struct binNode *) malloc (size );
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
treePtr=attach(treePtr,newNode);
}
}
return treePtr;
}
struct binNode *attach(struct binNode *tree,struct binNode *node)
{
if (tree==NULL)
tree=node;
else
{
if (node->val<tree->val)
tree->left=attach(tree->left,node);
else
tree->right=attach(tree->right,node);
}
return tree;
}
void inOrderTravel(struct binNode *binTree)
{
if( binTree==NULL)
return ;
inOrderTravel(binTree->left);
inOrderTravel(binTree->right);
printf("%d-",binTree->val);
}
ASSIGNMENT NO. –9
OBJECTIVE:- Implement the following programs with the help of Binary Search Tree
#include<stdio.h>
#include<malloc.h>
struct binNode
{
int val;
struct binNode *left,*right;
};
struct binNode *createbinTree();
struct binNode *attach(struct binNode *tree, struct binNode *node);
struct binNode *insertBST(struct binNode *binTree,int val,int *flag);
void inOrderTravel(struct binNode *binTree);
void main()
{
int result,val;
struct binNode *binTree;
binTree=createbinTree();
printf("\nEnter the value to be inserted:");
scanf("%d",&val);
binTree=insertBST(binTree,val,&result);
if(result==1)
{
printf("\nInsertion Successful:");
inOrderTravel(binTree);
}
else
printf("\nDuplicate value");
}
struct binNode *createbinTree()
{
int val,size;
struct binNode *treePtr,*newNode;
treePtr=NULL;
val=0;
size=sizeof(struct binNode);
while(val>=0)
{
printf("\nEnter the val");
scanf("%d",&val);
if (val>=0)
{
newNode=(struct binNode *) malloc (size );
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
treePtr=attach(treePtr,newNode);
}
}
return treePtr;
}
struct binNode *attach(struct binNode *tree,struct binNode *node)
{
if (tree==NULL)
tree=node;
else
{
if (node->val<tree->val)
tree->left=attach(tree->left,node);
else
tree->right=attach(tree->right,node);
}
return tree;
}
struct binNode *insertBST(struct binNode *binTree, int val,int *flag)
{
int size;
struct binNode *ptr;
size= sizeof(struct binNode);
if(binTree==NULL)
{
ptr=(struct binNode *)malloc (size);
ptr->val=val;
ptr->left=NULL;
ptr->right=NULL;
binTree=ptr;
*flag=1;
return binTree;
}
if(val==binTree->val)
{
*flag=0;
return binTree;
}
else
if(val<binTree->val)
binTree->left=insertBST(binTree->left,val,flag);
else
binTree->right=insertBST(binTree->right,val,flag);
return binTree;
}
void inOrderTravel(struct binNode *binTree)
{
if( binTree==NULL)
return ;
inOrderTravel(binTree->left);
printf("%d-",binTree->val);
inOrderTravel(binTree->right);
}
if(result==1)
{
printf("\nSearch Successful");
}
else
printf("Search Un-Successful");
}
struct binNode *createbinTree()
{
int val,size;
struct binNode *treePtr,*newNode;
treePtr=NULL;
val=0;
size=sizeof(struct binNode);
while(val>=0)
{
printf("\nEnter the val");
scanf("%d",&val);
if (val>=0)
{
newNode=(struct binNode *) malloc (size );
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
treePtr=attach(treePtr,newNode);
}
}
return treePtr;
}
struct binNode *attach(struct binNode *tree,struct binNode *node)
{
if (tree==NULL)
tree=node;
else
{
if (node->val<tree->val)
tree->left=attach(tree->left,node);
else
tree->right=attach(tree->right,node);
}
return tree;
}
/*void inOrderTravel(struct binNode *binTree)
{
if( binTree==NULL)
return ;
inOrderTravel(binTree->left);
printf("%d-",binTree->val);
inOrderTravel(binTree->right);
}*/
int searchBST (struct binNode *binTree,int val)
{
int flag;
if(binTree==NULL)
return 0;
if (val==binTree->val)
return 1;
else
if(val<binTree->val)
flag=searchBST(binTree->left,val);
else
flag=searchBST(binTree->right,val);
return flag; }
(3) Write a program in C to delete a node from binary search tree
Solution
#include<stdio.h>
#include<malloc.h>
struct binNode
{
int val;
struct binNode *left,*right;
};
struct binNode *createbinTree();
struct binNode *attach(struct binNode *tree, struct binNode *node);
struct binNode *searchBST(struct binNode *binTree,int val,int *flag);
struct binNode *findParent(struct binNode *binTree, struct binNode *ptr);
struct binNode *delNodeBST(struct binNode *binTree, int val,int *flag);
struct binNode *findSucc(struct binNode *ptr);
binTree=delNodeBST(binTree,val,&result);
if(result==1)
{
printf("\nDeletion Successful");
inOrderTravel(binTree);
}
else
printf("\nNode not present in tree");
}
struct binNode *createbinTree()
{
int val,size;
struct binNode *treePtr,*newNode;
treePtr=NULL;
val=0;
size=sizeof(struct binNode);
while(val>=0)
{
printf("\nEnter the val");
scanf("%d",&val);
if (val>=0)
{
newNode=(struct binNode *) malloc (size );
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
treePtr=attach(treePtr,newNode);
}
}
return treePtr;
}
struct binNode *attach(struct binNode *tree,struct binNode *node)
{
if (tree==NULL)
tree=node;
else
{
if (node->val<tree->val)
tree->left=attach(tree->left,node);
else
tree->right=attach(tree->right,node);
}
return tree;
}
struct binNode *delNodeBST (struct binNode *binTree,int val,int *flag)
{
int size, nval;
struct binNode *ptr,*parent,*succPtr;
if(binTree==NULL)
{
*flag=0;
return binTree;
}
ptr=searchBST(binTree,val,flag);
if(*flag==1)
parent=findParent(binTree,ptr);
else
return binTree;
if(ptr->left==NULL && ptr->right==NULL)
{
if(parent->left==ptr)
parent->left=NULL;
else
if(parent->right==ptr)
parent->right==NULL;
free(ptr);
}
if(ptr->left!=NULL && ptr->right==NULL)
{
if (parent ->left==ptr)
parent->left=ptr->left;
else
if(parent->right==ptr)
parent->right=ptr->left;
free(ptr);
return binTree;
}
else
if (ptr->left==NULL && ptr->right!=NULL)
{
if(parent->left==ptr)
parent->left=ptr->right;
else
if(parent->right==ptr)
parent->right=ptr->right;
free(ptr);
return binTree;
}
if(ptr->left!=NULL && ptr->right!=NULL)
{
succPtr=findSucc(ptr);
nval=succPtr->val;
delNodeBST(binTree, succPtr->val,flag);
ptr->val=nval;
}
return binTree;
}
void inOrderTravel(struct binNode *binTree)
{
if( binTree==NULL)
return ;
inOrderTravel(binTree->left);
printf("%d-",binTree->val);
inOrderTravel(binTree->right);
}
struct binNode *searchBST (struct binNode *binTree,int val,int *flag)
{
if(binTree==NULL)
{
*flag=0;
return binTree;
}
else
{
if (val==binTree->val)
{
*flag=1;
return binTree;
}
else
{
if(val<binTree->val)
return searchBST(binTree->left,val,flag);
else
return searchBST(binTree->right,val,flag);
}
}
}
struct binNode *findSucc(struct binNode *ptr)
{
struct binNode *succPtr;
succPtr=ptr->right;
while(succPtr->left!=NULL)
succPtr=succPtr->left;
return succPtr;
}
struct binNode *findParent(struct binNode *binTree,struct binNode *ptr)
{
struct binNode *pt;
if(binTree==NULL)
return binTree;
else
{
if(binTree->left==ptr || binTree->right==ptr)
{
pt=binTree;
return pt;
}
else
{
if(ptr->val<binTree->val)
pt=findParent(binTree->left,ptr);
else
pt=findParent(binTree->right,ptr);
}
}
return pt;
}
ASSIGNMENT NO. –10
1. Write a program to implement the BFS algorithm with the help of graph.
Program:
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v)
{
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main()
{
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
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]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
else
printf("\n Bfs is not possible");
getch();
}
2. Write a program to implement the DFS algorithm with the help of graph.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
/* ADJACENCY MATRIX */
int source,V,E,time,visited[20],G[20][20];
void DFS(int i)
{
int j;
visited[i]=1;
printf(" %d->",i+1);
for(j=0;j<V;j++)
{
if(G[i][j]==1&&visited[j]==0)
DFS(j);
}
}
int main()
{
int i,j,v1,v2;
printf("\t\t\tGraphs\n");
printf("Enter the no of edges:");
scanf("%d",&E);
printf("Enter the no of vertices:");
scanf("%d",&V);
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
G[i][j]=0;
}
/* creating edges :P */
for(i=0;i<E;i++)
{
printf("Enter the edges (format: V1 V2) : ");
scanf("%d%d",&v1,&v2);
G[v1-1][v2-1]=1;
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
printf(" %d ",G[i][j]);
printf("\n");
}
printf("Enter the source: ");
scanf("%d",&source);
DFS(source-1);
return 0;
}
(3) Write a program to implement the prim’s algorithm for Minimum cost spanning
tree.
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
clrscr();
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
getch();
}
(4) Write a program to implement the kruskal’s algorithm for Minimum cost spanning
tree.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
clrscr();
printf("\n\n\tImplementation of Kruskal's algorithm\n\n");
printf("\nEnter the no. of vertices\n");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of Minimum Cost Spanning Tree are\n\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("\n%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
getch();
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
1. Write a program to input how many numbers and then input the numbers and
then search any number with the help of sequential/Linear search.
PROGRAM:
#include <stdio.h>
void main()
{
int array[10];
int i, num, keynum, found = 0;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is: \n");
for (i = 0; i < num; i++)
{
printf("%d", array[i]);
}
printf("\n Enter the element to be searched \n");
scanf("%d", &keynum);
/* Linear search begins */
for (i = 0; i < num ; i++)
{
if (keynum == array[i] )
{
found = 1;
break;
}
}
if (found == 1)
printf("Element is present in the array\n");
else
printf("Element is not present in the array\n");
}
2. Write a program to input how many numbers and then input the numbers and
then search any number with the help of Binary search.
PROGRAM:
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
ASSIGNMENT NO. –12
(1) Write a program to input 10 numbers and then sort that numbers with the help
of bubble sort.
Solution
#include<stdio.h>
void main()
{
int array[100],size,i,j,temp;
printf("Enter the size of the array:");
scanf("%d",&size);
printf("\nEnter the elements:");
for(i=0;i<size;i++)
{
scanf("\n%d",&array[i]);
}
for(i=0;i<size;i++)
{
for(j=0;j<size-i-1;j++)
{
if(array[j+1]<array[j])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
printf("\nThe sorted array is:");
for(i=0;i<size;i++)
{
printf("\n%d",array[i]);
}
}
(2) Write a program to input 10 numbers and then sort that numbers with the help
of Selection sort.
Solution
#include<stdio.h>
void main()
{
int array[100],size,i,j,temp,pos;
printf("Enter the size of the array:");
scanf("%d",&size);
printf("\nEnter the elements:");
for(i=0;i<size;i++)
{
scanf("\n%d",&array[i]);
}
for(i=0;i<size;i++)
{
pos=i;
temp=array[i];
for(j=i+1;j<size;j++)
{
if(array[j]<temp)
{
temp=array[j];
pos=j;
}
temp=array[i];
array[i]=array[pos];
array[pos]=temp;
}
}
printf("\nThe sorted array is:");
for(i=0;i<size;i++)
{
printf("\n%d",array[i]);
}
}
(3) Write a program to input 10 numbers and then sort that numbers with the help
of Insertion sort.
Solution
#include<stdio.h>
void main()
{
int array[100],size,i,j,temp;
printf("Enter the size of the array:");
scanf("%d",&size);
printf("\nEnter the elements:");
for(i=0;i<size;i++)
{
scanf("\n%d",&array[i]);
}
for(i=1;i<size;i++)
{
temp=array[i];
j=i-1;
while(j>=0 && temp<=array[j])
{
array[j+1]=array[j];
j--;
}
array[j+1]=temp;
}
printf("\nThe sorted array is:");
for(i=0;i<size;i++)
{
printf("\n%d",array[i]);
}
}
ASSIGNMENT NO. –13
(1) Write a program to input 10 numbers and then sort that numbers with the help
of Merge sort.
Solution
#include<stdio.h>
Solution
#include <stdio.h>
#include <stdlib.h>
#define lchild(j) ((2 * j) + 1)
Program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
int getNumberOfDays(int month,int year)
{
switch(month)
{
case 1 : return(31);
case 2 : if(year%4==0)
return(29);
else
return(28);
case 3 : return(31);
case 4 : return(30);
case 5 : return(31);
case 6 : return(30);
case 7 : return(31);
case 8 : return(31);
case 9 : return(30);
case 10: return(31);
case 11: return(30);
case 12: return(31);
default: return(-1);
}
}
char *getName(int odd)
{
switch(odd)
{
case 0 :return("Sunday");
case 1 :return("Monday");
case 2 :return("Tuesday");
case 3 :return("Wednesday");
case 4 :return("Thursday");
case 5 :return("Friday");
case 6 :return("Saturday");
default:return("Error in getName() module.Invalid argument
passed");
}
}
int getOddNumber(int day,int mon,int year)
{
int res=0,t1,t2,y=year;
year = year-1600;
while(year>=100)
{
res=res+5;
year=year-100;
}
res=(res%7);
t1=((year-1)/4);
t2=(year-1)-t1;
t1=(t1*2)+t2;
t1=(t1%7);
res = res+t1;
res=res%7;
t2=0;
for(t1=1;t1<mon;t1++)
{
t2+=getNumberOfDays(t1,y);
}
t2 = t2+day;
t2 = t2%7;
res = res+t2;
res = res%7;
if(y>2000)
res=res+1;
res = res%7;
return res;
}
char *getWeek(int dd,int mm,int yy)
{
int odd;
if(!(mm>=1 && mm<=12))
{
return("Invalid month value");
}
if(!(dd>=1 && dd<=getNumberOfDays(mm,yy)))
{
return("Invalid date");
}
if(yy>=1600)
{
odd = getOddNumber(dd,mm,yy);
odd=odd%7;
return(getName(odd));
}
else
{
return("
Please give year more than 1600");
}
}
void printMonth(int mon,int year,int x,int y)
{
int nod,odd,cnt,d=1,x1=x,y1=y;
if(!(mon>=1 && mon<=12))
{
printf("
INVALID MONTH");
getch();
return;
}
if(!(year>=1600))
{
printf("
INVALID YEAR");
getch();
return;
}
if(x<=0)
x=wherex();
if(y<=0)
y=wherey();
gotoxy(x,y);
textcolor(RED);
cprintf("S");
textcolor(YELLOW);
cprintf(" M T W T F S");
/* 1234567891234567891234567 */
textcolor(7);
cprintf("");
y++;
nod=getNumberOfDays(mon,year);
odd=getOddNumber(d,mon,year);
switch(odd)
{
case 0 : x=x;
cnt=1;
break;
case 1 : x=x+4;
cnt=2;
break;
case 2 : x=x+8;
cnt=3;
break;
case 3 : x=x+12;
cnt=4;
break;
case 4 : x=x+16;
cnt=5;
break;
case 5 : x=x+20;
cnt=6;
break;
case 6 : x=x+24;
cnt=7;
break;
default : printf("
");
printMonth(mm,yy,-1,-1);
flushall();
getch();
break;
case '0' : exit(0);
}
}
}
ASSIGNMENT NO. –15
Program:
#include <stdio.h>
char fname[20];
char lname[20];
char sub_taken[20];
char last_edu[20];
char join_date[20];
int id;
int age;
float bsal;
}Employee;
int main(void)
int id;
FILE *fp,*ft;
char another,choice;
Employee emp;
char fname[20];
char lname[20];
fp=fopen("EMP.DAT","rb+");
if(fp==NULL)
{
fp=fopen( "EMP.DAT","wb+");
if(fp==NULL)
printf("
exit();
recsize=sizeof(emp);
while(1)
printf("
1.Add Records
2.Delete Records
3.Modify Records
4.List
Records
5.Exit");
printf("
fflush(stdin);
scanf("%c",&choice);
switch(choice)
case'1':
fseek(fp,0,SEEK_END);
another='Y';
while(another=='Y'|| another=='y')
scanf("%s %d %f",emp.fname,&emp.age,&emp.bsal);
printf("
scanf("%s %d %s
%s",emp.join_date,&emp.id,emp.last_edu,
emp.sub_taken);
fwrite(&emp,recsize,1,fp);
printf("
fflush(stdin);
another=getchar();
break;
case '2':
another='Y';
while(another=='Y'|| another=='y')
printf("
scanf("%d",&id);
ft=fopen("TEMP.DAT","wb");
rewind(fp);
while(fread(&emp,recsize,1,fp)==1)
if(strcmp(emp.id,id)!=0)
fwrite(&emp,recsize,1,ft);
fclose(fp);
fclose(ft);
remove("EMP.DAT");
rename("TEMP.DAT","EMP.DAT");
fp=fopen("EMP.DAT","rb+");
fflush(stdin);
another=getchar();
break;
case '3':
another='Y';
while(another=='Y'|| another=='y')
printf("
scanf("%s",emp.fname);
rewind(fp);
while(fread(&emp,recsize,1,fp)==1)
{
if(strcmp(emp.id,id)==0)
printf("
scanf("%s%s%d%f%s%s%s",emp.fname,emp.lname,&emp.age,&emp.bsal,emp.join_dat
e,emp.sub_taken,emp.last_edu);
fseek(fp,-recsize,SEEK_CUR);
fwrite(&emp,recsize,1,fp);
break;
printf("
fflush(stdin);
another=getchar();
break;
case '4':
rewind(fp);
while(fread(&emp,recsize,1,fp)==1)
printf("
%s %s %d
%g",emp.fname,emp.lname,emp.age,emp.bsal,emp.join_date,emp.last_edu,emp.su
b_taken);
break;
case '5':
fclose(fp);
exit();