Download marri laxman reddy

Document related concepts
no text concepts found
Transcript
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
MARRI EDUCATIONAL SOCIETY’S GROUP OF INSTITUTIONS
MARRI LAXMAN REDDY
INSTITUTE OF TECHNOLOGY & MANAGEMENT
(Approved by AICTE, New Delhi & Affiliated JNTU, Hyderabad)
Dundigal, Quthbullapur, Hyderabad – 500 043, R.R.Dist., A.P., INDIA
www.mlritm.ac.in, 08418-25554/55
Data Structure Through C Lab Manual
II B.TECH CSE II-SEMISTER
DEPARTMENT OF COMPUTER SCIENCE
AND ENGINEERING
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Index
Week No
Experiment Name
1
Write a C program that uses functions to perform the following:
a) Create a singly linked list of integers.
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.
2
Write a C program that uses functions to perform the following:
a) Create a doubly linked list of integers.
b) Delete a given integer from the above doubly linked list.
c) Display the contents of the above list after deletion.
3
Write a C program that uses stack operations to convert a given infix expression into
its postfix Equivalent, Implement the stack using an array.
4
Write C programs to implement a double ended queue ADT using i)array and
ii)doubly linked list respectively.
5
Write a C program that uses functions to perform the following:
a) Create a binary search tree of characters.
b) Traverse the above Binary search tree recursively in Postorder.
6
Write a C program that uses functions to perform the following:
a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non recursively in inorder
7
Write C programs for implementing the following sorting methods to arrange a list of
integers in Ascending order :
a) Insertion sort b) Merge sort
8
Write C programs for implementing the following sorting methods to arrange a list of
integers in ascending order:
a) Quick sort
b) Selection sort
9
i) Write a C program to perform the following operation:
a)Insertion into a B-tree.
ii) Write a C program for implementing Heap sort algorithm for sorting a given list of
integers in ascending order.
10
Write a C program to implement all the functions of a dictionary (ADT) using hashing.
11
Write a C program for implementing Knuth-Morris- Pratt pattern matching algorithm.
12
Write C programs for implementing the following graph traversal algorithms:
a)Depth first traversal
b)Breadth first traversal
Page No
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Additional Programs
1) Implement a Stack using arrays
2) Implement a Stack using Linked List
3) Implement a Queue using arrays
4) Implement a Queue using Linked List
5) Implement a Circular Queue
6) Evaluate a Post fix Expression using stack
7) Implement Linear hashing Technique
8) Implement a sparse matrix using arrays
9) Implement a Linear Search with Recursive
10) Implement a Linear Search with Non Recursive
11) Implement a Binary Search with Recursive
12) Implement a Binary Search with Non Recursive
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Ds Additional problem statements of week 1
1) Write a c program to perform the following functions
a) create a SLL of integers between 1 to 100.
b) Delete the nodes which are even numbers from above list
c)Display all the odd numbers of the above list after deletion.
Test Case 1: 6,55,96
Display: 6,55,96
Deletion: 6,96 deleted
Display: 55
Test Case 2: 87,155,196
Wrong Input (out of range)
2) Write a c program to perform the following functions
a) create a SLL of integers between 1 to 100.
b) Delete the nodes which are odd numbers from above list
c)Display all the even numbers of the above list after deletion.
Test Case 1: 6,55,96
Display: 6,55,96
Deletion: 55 deleted
Display: 6,96
Test Case 2: 87,155,196
Wrong Input (out of range)
3) Write a c program to perform the following functions
a) create a SLL of characters.
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
b) Delete the nodes which are vowel characters from above list
c)Display all in the list after deletion.
Test Case 1: B I Z X O
Display: B I Z X O
Deletion: I O deleted
Display: B Z X
4)Write a c program to perform the following functions
a) create a SLL of integers.
b) Delete a node at 2nd position from above list
c)Display all nodes in above list after deletion.
Test Case 1: 6,55,96
Display: 6,55,96
Deletion: 55 deleted
Display: 6,96
5)Write a c program to perform the following functions
a) create a SLL of integers divisible by 10.
b) Delete a node at end position from above list
c)Display all nodes in above list after deletion.
Test Case 1: 10,20,30
Display: 10,20,30
Deletion: 30 deleted
Display: 10,20
Test Case 2: 87,155,196
Wrong Input
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
6) Write a c program to perform the following functions
a) create a SLL of integers.
b) Insert an element 9 at position 3
c)Display all nodes in above list.
Test Case 1: 10,20,30
Display: 10,20,30
Insert : 9 at pos 3
Display: 10,20,9,30
7) Write a c program to perform the following functions
a) create a SLL of integers.
b) Insert an element at middle position
c)Display all nodes in above list.
Test Case 1: 10,20,30,40
Display: 10,20,30,40
Insert : 9
Display: 10,20,9,30,40
Program 8
Create a Single Linked List of integers
a) Count the number of nodes in the list
Test case 1: 1, 3, 7, 9, 10, 11
Count: 6
Test case 2: 20, 30, 40, 50, 70
Count: 5
Program 9
a) Create a Single Linked List of integers
b) Find maximum number in the list
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
c) Find the minimum number in the list
Test case 1: 10, 23, 7, 19, 10, 4, 35, 46, 2
Maximum number: 46
Minimum number: 2
Program 10
a) Create a linked list of integers
b) Find the sum of all the elements in the list
Test case : 10,11, 12, 14, 15
Sum : 62
Program 11
a) Create a Single Linked List of integers
b) Display the elements in the reverse order
Test case : 1,2,3,4,5
Display: 5, 4, 3, 2,1
Ds Additional problem statements of week 2
1) Write a c program to perform the following functions
a) create a DLL of integers between 1 to 100.
b) Delete the nodes which are even numbers from above list
c)Display all the odd numbers of the above list after deletion.
Test Case 1: 6,55,96
Display: 6,55,96
Deletion: 6,96 deleted
Display: 55
Test Case 2: 87,155,196
Wrong Input (out of range)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
2) Write a c program to perform the following functions
a) create a DLL of integers between 1 to 100.
b) Delete the nodes which are odd numbers from above list
c)Display all the even numbers of the above list after deletion.
Test Case 1: 6,55,96
Display: 6,55,96
Deletion: 55 deleted
Display: 6,96
Test Case 2: 87,155,196
Wrong Input (out of range)
3) Write a c program to perform the following functions
a) create a DLL of characters.
b) Delete the nodes which are vowel characters from above list
c)Display all in the list after deletion.
Test Case 1: B I Z X O
Display: B I Z X O
Deletion: I O deleted
Display: B Z X
4)Write a c program to perform the following functions
a) create a DLL of integers.
b) Delete a node at 2nd position from above list
c)Display all nodes in above list after deletion.
Test Case 1: 6,55,96
Display: 6,55,96
Deletion: 55 deleted
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Display: 6,96
5)Write a c program to perform the following functions
a) create a DLL of integers divisible by 10.
b) Delete a node at end position from above list
c)Display all nodes in above list after deletion.
Test Case 1: 10,20,30
Display: 10,20,30
Deletion: 30 deleted
Display: 10,20
Test Case 2: 87,155,196
Wrong Input
6) Write a c program to perform the following functions
a) create a DLL of integers.
b) Insert an element 9 at position 3
c)Display all nodes in above list.
Test Case 1: 10,20,30
Display: 10,20,30
Insert : 9 at pos 3
Display: 10,20,9,30
7) Write a c program to perform the following functions
a) create a DLL of integers.
b) Insert an element at middle position
c)Display all nodes in above list.
Test Case 1: 10,20,30,40
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Display: 10,20,30,40
Insert : 9
Display: 10,20,9,30,40
Program 8
Create a DLL of integers
b) Count the number of nodes in the list
Test case 1: 1, 3, 7, 9, 10, 11
Count: 6
Test case 2: 20, 30, 40, 50, 70
Count: 5
Program 9
d) Create a DLL of integers
e) Find maximum number in the list
f) Find the minimum number in the list
Test case 1: 10, 23, 7, 19, 10, 4, 35, 46, 2
Maximum number: 46
Minimum number: 2
Program 10
c) Create a DLL of integers
d) Display the elements in the reverse order
Test case : 1,2,3,4,5
Display: 5, 4, 3, 2,1
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week1: Write a C program that uses functions to perform the following:
a) Create a singly linked list of integers.
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.
AIM: Implement the Single linked List
Algorithms:
Inserting a node into SLL:
Algorithm: Insert at front()
{
Allocate a memory for new node(new1)
if (new1== NULL)
then
display memory is full (insertion is not possible)
end if
else
read element ele;
new1->data=ele;/*copy the data into new1 node */
new1->next=header->next;
header->next=new1;
end else
}
Algorithm: Insert at End()
{
Allocate a memory for new node(new1)
if(new1== NULL)
then
display memory is full (insertion is not possible)
end if
else
ptr=header
while(ptr->next!=NULL )/*ptr moves end of list */
then
ptr=ptr->next
end
new1->next=NULL
new1->data=ele
ptr->next=new1
end else
}
Algorithm: Insert at middle ()
{
Allocate a memory for new node(new1)
if (new1== NULL)
then
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
display memory is full (insertion is not possible)
exit
else
read ele,pos
ptr=header
count=0
while(ptr->next!=NULL)
{
ptr=ptr->next;
count ++;
}
if(count<pos-1)
then
display position is not of range
end
ptr=header
count=0
while(count<pos-1)
then
ptr=ptr->next
count++
end
new1->data=ele
new1->next=ptr->next
ptr->next=new1
end else
}
Deleting a node from the SLL:
Algorithm: Delete at front()
{
if (header->next==NULL)
then
display list is empty
end if
else
temp=header->next;
header->next=header->next->next;
free(temp);
end if
}
Algorithm: Delete at end()
{
if(header->next==NULL)
then
display list is empty
end if
else
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
ptr=header;
while(ptr->next->next!=NULL)
{
ptr->=Ptr->next;
}
temp=ptr->next;
ptr->next=NULL;
free(temp);
end else
}
Algorithm:delete at anyposition()
{
if (header->next==NULL)
then
display list is empty /*deletion is not possible*/
end if
ptr=header;
count=0;
while(ptr->next!=NULL)
{
ptr=ptr->next;
count++;
}
if(count<pos-1)
{
Display position is out of range
}
ptr=header;
count=0;
while(count<pos-1)
{
ptr=ptr->next;
count++;
}
temp=ptr->next;
ptr->next=temp->next;
free(temp)
}
Traversing a List:
Algorithm:Traverse()
{
ptr=header;
if(ptr ->next==NULL)
then
display list is empty
end if
else
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
while(ptr -> next!=NULL)
{
display ptr-> data
ptr=ptr -> next
/* move to next node */
}
end if
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Program:
/*Implement a SLL*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *header=NULL;
struct node *ptr=NULL,*temp=NULL;
void create();
void insert_at_front();
void insert_at_end();
void insert_at_middle();
void delete_at_front();
void delete_at_end();
void delete_at_middle();
void display();
int main()
{
int ch;
header=(struct node*)malloc(sizeof(struct node));
header->next=NULL;
ptr=header;
//clrscr();
printf("\n\n1.create \n2- insert at front\n3-insert at middle\n4-insert at end\n5display\n6.delete_at_front\n7.delete_at_middle\n8.delete_at_end\n9-exit");
while(1)
{
printf("\nenter ur choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: create();
break;
case 2: insert_at_front();
break;
case 3: insert_at_middle();
break;
case 4: insert_at_end();
break;
case 5: display();
break;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
case 6: delete_at_front();
break;
case 7: delete_at_middle();
break;
case 8: delete_at_end();
break;
case 9: exit(0);
default: printf("wrong choice");
}
}
}
void create()
{
char ch;
while(1)
{
insert_at_end();
printf("if u want to continue press 'y' or 'n' :");
scanf("\n%c",&ch);
if(ch=='y'||ch=='Y')
continue;
else
break;
}
}
void insert_at_front()
{
int ele;
struct node *new1;
new1=(struct node*)malloc(sizeof(struct node));
if(new1==NULL)
{
printf("out of space");
return;
}
printf("enter ele:");
scanf("%d",&ele);
new1->next=header->next;
header->next=new1;
new1->data=ele;
printf("inserted successfully");
}
void insert_at_end()
{
struct node *new1;
int ele;
new1=(struct node*)malloc(sizeof(struct node));
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
ptr=header;
if(new1==NULL)
{
printf("out of space");
return;
}
printf("enter Inserted ele:");
scanf("%d",&ele);
/* Move the pointer to upto end of the node*/
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
new1->next=NULL;
ptr->next=new1;
new1->data=ele;
printf("inserted successfully");
}
void insert_at_middle()
{
struct node *new1;
int ele;
int pos,count=0;
new1=(struct node*)malloc(sizeof(struct node));
ptr=header;
if(new1==NULL)
{
printf("out of space");
return;
}
printf("enter Inserted ele:");
scanf("%d",&ele);
printf("enter where it to be inserted at what position number:");
scanf("%d",&pos);
/* Calculate the no of elements in the list */
while(ptr->next!=NULL)
{
count++;
ptr=ptr->next;
}
/*Compare the entered positions number is valid or not using count the no.of elements
in the list*/
if(count<pos)
{
printf("pos is out of range");
return;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
ptr=header;
count=0;
/*Move the ptr upto particular entered position number*/
while(count<pos-1)
{
ptr=ptr->next;
count++;
}
new1->next=ptr->next;
ptr->next=new1;
new1->data=ele;
printf("inserted successfully");
}
void display()
{
ptr=header;
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty");
return;
}
while(ptr->next!=NULL)
{
printf("%d -> ",ptr->next->data);
ptr=ptr->next;
}
printf("NULL");
}
void delete_at_front()
{
ptr=header;
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty deletion is not possible");
return;
}
temp=ptr->next;
ptr->next=ptr->next->next;
free(temp);
printf("deleted succssfully");
}
void delete_at_end()
{
ptr=header;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty deletion is not possible");
return;
}
/*Move the ptr upto last but one node*/
while(ptr->next->next!=NULL)
{
ptr=ptr->next;
}
temp=ptr->next;
ptr->next=NULL;
free(temp); /* Clear the Memory*/
printf("deleted succssfully");
}
void delete_at_middle()
{
int pos,count;
ptr=header;
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty deletion is not possible");
return;
}
count=0;
/* Calculate the no.of elements in the list */
while(ptr->next!=NULL)
{
ptr=ptr->next;
count++;
}
printf("enter deleted position number:");
scanf("%d",&pos);
/*Compare the entered positions number is valid or not using count the no.of elements in
the list*/
if(count<pos)
{
printf("position is out of range");
return;
}
ptr=header;
count=0;
/*Move the ptr upto particular entered position number*/
while(ptr->next->next!=NULL&&count<pos-1)
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
ptr=ptr->next;
count++;
}
temp=ptr->next;
ptr->next=ptr->next->next;
free(temp);
printf("deleted succssfully");
}
/*OUTPUT:
1.create
2- insert at front
3-insert at middle
4-insert at end
5-display
6.delete_at_front
7.delete_at_middle
8.delete_at_end
9-exit
enter ur choice : 1
enter Inserted ele:10
inserted successfullyif u want to continue press 'y' or 'n' :y
enter Inserted ele:20
inserted successfullyif u want to continue press 'y' or 'n' :y
enter Inserted ele:30
inserted successfullyif u want to continue press 'y' or 'n' :n
enter ur choice : 5
10 -> 20 -> 30 -> NULL
enter ur choice : 2
enter ele:15
inserted successfully
enter ur choice : 5
15 -> 10 -> 20 -> 30 -> NULL
enter ur choice : 3
enter Inserted ele:25
enter where it to be inserted at what position number:2
inserted successfully
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
enter ur choice : 5
15 -> 25 -> 10 -> 20 -> 30 -> NULL
enter ur choice : 4
enter Inserted ele:35
inserted successfully
enter ur choice : 5
15 -> 25 -> 10 -> 20 -> 30 -> 35 -> NULL
enter ur choice : 6
deleted succssfully
enter ur choice : 5
25 -> 10 -> 20 -> 30 -> 35 -> NULL
enter ur choice : 7
enter deleted position number:2
deleted succssfully
enter ur choice : 5
25 -> 20 -> 30 -> 35 -> NULL
enter ur choice : 8
deleted succssfully
enter ur choice : 5
25 -> 20 -> 30 -> NULL
enter ur choice : 9
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week2: Write a C program that uses functions to perform the following:
a) Create a doubly linked list of integers.
b) Delete a given integer from the above doubly linked list.
c) Display the contents of the above list after deletion.
AIM: Implement the Single linked List
Algorithms:
Inserting a node into DLL:
Algorithm: Insert at front()
{
Allocate a memory for new node(new1)
if (new1== NULL)
then
display memory is full (insertion is not possible)
end if
else
read element ele;
new1->data=ele;/*copy the data into new1 node */
new1->next=header->next;
header->next->prev=new1;
header->next=new1;
new1->prev=header;
end else
}
Algorithm: Insert at End()
{
Allocate a memory for new node(new1)
if(new1== NULL)
then
display memory is full (insertion is not possible)
end if
else
ptr=header
while(ptr->next!=NULL )/*ptr moves end of list */
then
ptr=ptr->next
end
new1->next=NULL
new1->prev=ptr;
new1->data=ele
ptr->next=new1
end else
}
Algorithm: Insert at middle ()
{
Allocate a memory for new node(new1)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
if (new1== NULL)
then
display memory is full (insertion is not possible)
exit
else
read ele,pos
ptr=header
count=0
while(ptr->next!=NULL)
{
ptr=ptr->next;
count ++;
}
if(count<pos-1)
then
display position is not of range
end
ptr=header
count=0
while(count<pos-1)
then
ptr=ptr->next
count++
end
new1->data=ele;
new1->next=ptr->next;
new1->prev=ptr;
ptr->next->prev=new1;
ptr->next=new1
end else
}
Deleting a node from the DLL:
Algorithm: delete at front()
{
if (header->next==NULL)
then
display list is empty
end if
else
temp=header->next;
header->next=header->next->next;
temp->next->prev=header;
free(temp);
end if
}
Algorithm: Delete at end()
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
if(header->next==NULL)
then
display list is empty
end if
else
ptr=header;
while(ptr->next->next!=NULL)
{
ptr->=Ptr->next;
}
temp=ptr->next;
ptr->next=NULL;
free(temp);
end else
}
Algorithm:delete at anyposition()
{
if (header->next==NULL)
then
display list is empty /*deletion is not possible*/
end if
ptr=header;
count=0;
while(ptr->next!=NULL)
{
ptr=ptr->next;
count++;
}
if(count<pos-1)
{
Display position is out of range
}
ptr=header;
count=0;
while(count<pos-1)
{
ptr=ptr->next;
count++;
}
temp=ptr->next;
ptr->next=temp->next;
temp->next->prev=Ptr;
free(temp)
}
Traversing a List:
Algorithm:Traverse()
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
ptr=header;
if(ptr ->next==NULL)
then
display list is empty
end if
else
while(ptr -> next!=NULL)
{
display ptr-> data
ptr=ptr -> next
/* move to next node */
}
end if
}
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *header=NULL;
struct node *ptr=NULL,*temp=NULL;
void create();
void insert_at_front();
void insert_at_end();
void insert_at_middle();
void delete_at_front();
void delete_at_end();
void delete_at_middle();
void count();
void display();
void search();
int main()
{
int ch;
header=(struct node*)malloc(sizeof(struct node));
header->next=NULL;
header->prev=NULL;
ptr=header;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
//clrscr();
printf("\n\n1.create \n2- insert at front\n3-insert at middle\n4-insert at end\n5display\n6.delete_at_front\n7.delete_at_middle\n8.delete_at_end\\n9-exit");
while(1)
{
printf("\nenter ur choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: create();
break;
case 2: insert_at_front();
break;
case 3: insert_at_middle();
break;
case 4: insert_at_end();
break;
case 5: display();
break;
case 6: delete_at_front();
break;
case 7: delete_at_middle();
break;
case 8: delete_at_end();
break;
case 9: exit(0);
default: printf("wrong choice");
}
}
}
void create()
{
char ch;
while(1)
{
insert_at_end();
printf("if u want to continue press 'y' or 'n' :");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
continue;
else
break;
}
}
void insert_at_front()
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
int ele;
struct node *new1;
new1=(struct node*)malloc(sizeof(struct node));
if(new1==NULL)
{
printf("out of space");
return;
}
printf("enter ele:");
scanf("%d",&ele);
new1->next=header->next;
header->next->prev=new1;
header->next=new1;
new1->prev=header;
new1->data=ele;
printf("inserted successfully");
}
void insert_at_end()
{
struct node *new1;
int ele;
new1=(struct node*)malloc(sizeof(struct node));
ptr=header;
if(new1==NULL)
{
printf("out of space");
return;
}
printf("enter Inserted ele:");
scanf("%d",&ele);
/* Move the pointer to upto end of the node*/
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
new1->next=NULL;
new1->prev=ptr;
ptr->next=new1;
new1->data=ele;
printf("inserted successfully");
}
void insert_at_middle()
{
struct node *new1;
int ele;
int pos,count=0;
new1=(struct node*)malloc(sizeof(struct node));
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
ptr=header;
if(new1==NULL)
{
printf("out of space");
return;
}
printf("enter Inserted ele:");
scanf("%d",&ele);
printf("enter where it to be inserted at what position number:");
scanf("%d",&pos);
/* Calculate the no of elements in the list */
while(ptr->next!=NULL)
{
count++;
ptr=ptr->next;
}
/*Compare the entered positions number is valid or not using count the no.of elements in the
list*/
if(count<pos)
{
printf("pos is out of range");
return;
}
ptr=header;
count=0;
/*Move the ptr upto particular entered position number*/
while(count<pos-1)
{
ptr=ptr->next;
count++;
}
new1->next=ptr->next;
new1->prev=ptr;
ptr->next->prev=new1;
ptr->next=new1;
new1->data=ele;
printf("inserted successfully");
}
void display()
{
ptr=header;
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty");
return;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
while(ptr->next!=NULL)
{
printf("%u,%d,%u -> ",ptr->next->prev,ptr->next->data,ptr->next->next);
ptr=ptr->next;
}
printf("NULL");
}
void delete_at_front()
{
ptr=header;
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty deletion is not possible");
return;
}
temp=ptr->next;
ptr->next=ptr->next->next;
ptr->next->prev=ptr;
free(temp);
printf("deleted succssfully");
}
void delete_at_end()
{
ptr=header;
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty deletion is not possible");
return;
}
/*Move the ptr upto last but one node*/
while(ptr->next->next!=NULL)
{
ptr=ptr->next;
}
temp=ptr->next;
ptr->next=NULL;
free(temp); /* Clear the Memory*/
printf("deleted succssfully");
}
void delete_at_middle()
{
int pos,count;
ptr=header;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
/* Check the List is Empty or not*/
if(ptr->next==NULL)
{
printf("list is empty deletion is not possible");
return;
}
count=0;
/* Calculate the no.of elements in the list */
while(ptr->next!=NULL)
{
ptr=ptr->next;
count++;
}
printf("enter deleted position number:");
scanf("%d",&pos);
/*Compare the entered positions number is valid or not using count the no.of elements in
the list*/
if(count<pos)
{
printf("position is out of range");
return;
}
ptr=header;
count=0;
/*Move the ptr upto particular entered position number*/
while(ptr->next->next!=NULL&&count<pos-1)
{
ptr=ptr->next;
count++;
}
temp=ptr->next;
ptr->next=ptr->next->next;
ptr->next->prev=ptr;
free(temp);
printf("deleted succssfully");
}
/*OUTPUT:
1.create
2- insert at front
3-insert at middle
4-insert at end
5-display
6.delete_at_front
7.delete_at_middle
8.delete_at_end
9-exit
enter ur choice : 1
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
enter Inserted ele:10
inserted successfullyif u want to continue press 'y' or 'n' :n
enter ur choice : 5
28938256,10,0 -> NULL
enter ur choice : 2
enter ele:20
inserted successfully
enter ur choice : 5
28938256,20,28938288 -> 28938320,10,0 -> NULL
enter ur choice : 3
enter Inserted ele:25
enter where it to be inserted at what position number:2
inserted successfully
enter ur choice : 5
28938256,20,28938352 -> 28938320,25,28938288 -> 28938352,10,0 -> NULL
enter ur choice : 3
enter Inserted ele:35
enter where it to be inserted at what position number:3
inserted successfully
enter ur choice : 5
28938256,20,28938352 ->
28938384,10,0 -> NULL
28938320,25,28938384
->
28938352,35,28938288
enter ur choice : 6
deleted succssfully
enter ur choice : 5
28938256,25,28938384 -> 28938352,35,28938288 -> 28938384,10,0 -> NULL
enter ur choice : 7
enter deleted position number:2
deleted succssfully
enter ur choice : 5
28938256,25,28938288 -> 28938352,10,0 -> NULL
enter ur choice : 8
deleted succssfully
enter ur choice : 5
28938256,25,0 -> NULL
enter ur choice : 9
->
Data Structure Lab
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week3: Write a C program that uses stack operations to convert a given infix expression into
its postfix Equivalent, Implement the stack using an array.
Algorithm:
Step 1: Define a stack array.
Step 2: Scan each character in the infix string
Step 3: If it is between 0 to 9 or any alphabet, append it to postfix string.
Step 4: If it is left parenthesis push to stack
If it is operator *,+,-,/,%,^ then
If the stack is empty push it to the stack
If the stack is not empty then start a loop:
If the top of the stack has higher precedence
Then pop and append to output string
Else break
Push to the stack
If it is right parenthesis then
While stack not empty and top not equal to left brace
Pop from stack and append to output string
Finally pop out the left brace.
Step 5: If there is any input in the stack pop and append to the Postfix string.
Example:
Expression
A/B^C-D
Current
Symbol
Initial
State
Stack Output
Comment
NULL -
Initially Stack is Empty
/B^C-D
A
NULL A
Print Operand
B^C-D
/
/
A
Push Operator Onto Stack
^C-D
B
/
AB
Print Operand
C-D
^
/^
AB
Push Operator Onto Stack because Priority of ^ is
greater than Current Topmost Symbol of Stack i.e
‘/’
-D
C
/^
ABC
Print Operand
ABC^
Step 1 : Now ‘^’ Has Higher Priority than
Incoming Operator So We have to Pop Topmost
Element
.
Step 2 : Remove Topmost Operator From Stack
and Print it
NULL ABC^/
Step 1 : Now ‘/’ is topmost Element of Stack Has
Higher Priority than Incoming Operator So We
have to Pop Topmost Element again.
Step 2 : Remove Topmost Operator From Stack
and Print it
D
D
-
-
/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Step 1 : Now Stack Becomes Empty and We can
Push Operand Onto Stack
D
-
-
ABC^/
NULL
D
-
ABC^/D Print Operand
NULL
NULL
-
ABC^/D-
Expression Scanning Ends but we have still one
more element in stack so pop it and display it
Program:
/* convert infix to postfix expression.*/
#include<stdio.h>
void infix_to_postfix(char[],char[]);
int precedence(char);
void main()
{
char infix[20],postfix[20];
//clrscr();
printf("\n Enter the Infix experssion : ");
scanf("%s",infix);
infix_to_postfix(infix,postfix);
printf("\nPostfix expression is : %s",postfix);
}
void infix_to_postfix(char infix[],char postfix[])
{
char s[20],symbol;
int top=-1,i=0,j=0;
while(infix[i]!='\0')
{
symbol=infix[i];
switch(symbol)
{
case '(': ++top;
s[top]=symbol;
break;
case ')': while(s[top]!='(')
{
postfix[j++]=s[top];
top--;
}
top--;
break;
case '+':
case '-':
case '*':
case '^':
case '/':
while(precedence(symbol)<=precedence(s[top])&&top!=-1)
postfix[j++]=s[top--];
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
s[++top]=symbol;
break;
default:postfix[j++]=symbol;
}
i++;
}
while(top!=-1)
{
postfix[j++]=s[top];
top--;
}
postfix[j]='\0';
}
int precedence(char x)
{
switch(x)
{
case '+':
case '-': return(1);
case '*':
case '^': return(3);
case '/': return(2);
default: return(0);
}
}
/*OUTPUT-1:
[mm0528@agni DS]$ cc infix_postfix.c
[mm0528@agni DS]$ ./a.out
Enter the postfix experssion : a+b*c
Post fix expression is : abc*+
OUTPUT-2:
[mm0528@agni DS]$ ./a.out
Enter the postfix experssion : a+(b+c*d)*f
Post fix expression is : abcd*+f*+
OUTPUT-3:
[mm0528@agni DS]$ ./a.out
Enter the postfix experssion : a+(b*c+d)*f
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Post fix expression is : abc*d+f*+
OUTPUT-4:
[mm0528@agni DS]$ ./a.out
Enter the postfix experssion : a*(b*c+d)+f
Post fix expression is : abc*d+*f+
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 4:Write C programs to implement a double ended queue ADT using i)array and
ii)doubly linked list respectively.
Double-Ended Queue
A double-ended queue is an abstract data type similar to an simple queue, it allows you to
insert and delete from both sides means items can be added or deleted from the front or rear
end.
i) array
AIM: Implement a DEQUEUE using arrays
Algorithm for Insertion at rear end
Step -1: [Check for overflow]
if(rear==MAX)
Print("Queue is Overflow”);
return;
Step-2: [Insert element]
else
rear=rear+1;
q[rear]=no;
[Set rear and front pointer]
if rear=0
rear=1;
if front=0
front=1;
Step-3: return
Algorithm for Insertion at font end
Step-1 : [Check for the front position]
if(front<=1)
Print (“Cannot add item at front end”);
return;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Step-2 : [Insert at front]
else
front=front-1;
q[front]=no;
Step-3 : Return
Algorithm for Deletion from front end
Step-1 [ Check for front pointer]
if front=0
print(" Queue is Underflow”);
return;
Step-2 [Perform deletion]
else
no=q[front];
print(“Deleted element is”,no);
[Set front and rear pointer]
if front=rear
front=0;
rear=0;
else
front=front+1;
Step-3 : Return
Algorithm for Deletion from rear end
Step-1 : [Check for the rear pointer]
if rear=0
print(“Cannot delete value at rear end”);
return;
Step-2: [ perform deletion]
else
no=q[rear];
[Check for the front and rear pointer]
if front= rear
front=0;
rear=0;
else
rear=rear-1;
print(“Deleted element is”,no);
Step-3 : Return
Program:
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 4
int Queue[MAXSIZE],front=-1,rear=-1,i;
void insert_at_front();
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
void insert_at_rear();
void delete_at_front();
void delete_at_rear();
void display();
int main()
{
int ch;
printf("\n 1.insert at front\n 2.insert at rear\n 3.delete at front\n4.delete at rear\n5.DISPLAY\n
6.EXIT\n");
do
{
printf("\nenter your choice[1-6]:");
scanf("%d",&ch);
switch(ch)
{
case 1:insert_at_front();
break;
case 2:insert_at_rear();
break;
case 3:delete_at_front();
break;
case 4:delete_at_rear();
break;
case 5:display();
break;
case 6:exit(0);
default:printf("invalid option \n");
}
}while(1);
}
void insert_at_rear()
{
if(rear==MAXSIZE-1)
{
printf("queue is full(overflow)\n");
return;
}
rear++;
printf("enter the element to insert_at_rear:");
scanf("%d",&Queue[rear]);
if(front==-1)
front++;
}
void insert_at_front()
{
int num;
if(front<=1)
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
printf("\n Cannot add item at front end");
return;
}
else
{
front--;
printf("\n Enter item to insert:");
scanf("%d",&Queue[front]);
}
}
void delete_at_front()
{
if(front==-1)
{
printf("queue is empty(underflow)\n");
return;
}
printf("the delete_at_front element is:%d \n",Queue[front]);
if(front==rear)
front=rear=-1;
else
front++;
}
void delete_at_rear()
{
if(rear==-1)
{
printf("queue is empty(underflow)\n");
return;
}
printf("the delete_at_rear element is:%d \n",Queue[rear]);
if(front==rear)
front=rear=-1;
else
{
rear--;
}
}
void display()
{
if(front==-1)
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
printf("queue is empty(underflow)\n");
return;
}
printf("the element in queue are:front->");
for(i=front;i<=rear;i++)
printf("%d ",Queue[i]);
printf("<-REAR\n");
}
/*OUTPUT:
1.insert at front
2.insert at rear
3.delete at front
4.delete at rear
5.DISPLAY
6.EXIT
enter your choice[1-6]:2
enter the element to insert_at_rear:10
enter your choice[1-6]:2
enter the element to insert_at_rear:30
enter your choice[1-6]:5
the element in queue are:front->10 30 <-REAR
enter your choice[1-6]:2
enter the element to insert_at_rear:40
enter your choice[1-6]:5
the element in queue are:front->10 30 40 <-REAR
enter your choice[1-6]:3
the delete_at_front element is:10
enter your choice[1-6]:5
the element in queue are:front->30 40 <-REAR
enter your choice[1-6]:1
Enter item to insert:40
enter your choice[1-6]:5
the element in queue are:front->40 30 40 <-REAR
enter your choice[1-6]:4
the delete_at_rear element is:40
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
enter your choice[1-6]:5
the element in queue are:front->40 30 <-REAR
enter your choice[1-6]:6
*/
ii) Linked List
AIM: To implement a Double ended Queue using Linked List
Algorithm: display()
{
ptr = front; //assign the ptr to front node
if(front==NULL || rear==NULL)
{
printf("List is empty");
}
while(ptr != NULL)
{
Display ptr ->data
Pointer move to next node i.e: ptr = ptr->next;
}
}
Algorithm: insert_begin(x)
{
Allocate a memory for new node(new1)
new1 -> data =x;
new1 ->previous = new1 ->next =NULL;
if(front == NULL||rear==NULL)
front = rear = new1;
else
{
new1 ->next = front;
front ->previous = new1;
front = new1;
}
}
Algorithm: insert_last(x)
{
Allocate a memory for new node (new1)
new1 ->data = x;
new1 -> previous = new1 ->next = NULL;
if (front == NULL||rear==NULL)
front = rear = new1;
else
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
rear ->next = new1;
new1 ->previous = rear;
rear = new1;
}
}
Algorithm: delete_begin()
{
if (front == NULL || rear==NULL)
{
Display List is empty
}
else
{
temp = front;
/*assign the temp point at front node*/
x= temp->data;
if(front==rear) //verify list having only one node then update the list is
empty
{
front=NULL;
rear=NULL;
}
else
{
front = front->next;
front->previous = NULL;
}
count --;
// decrease the no.of nodes in the list
delete the temp node
}
}
Algorithm:
delete_last( )
{
if(rear == NULL || front==NULL)
{
Display List is empty
}
else
{
temp = rear;
/*assign the temp point at rear node*/
if(front==rear)
//verify list having only one node then update the list is
empty
{
front=NULL;
rear=NULL;
}
else
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
rear = rear->previous;
rear -> next = NULL;
}
x= temp ->data;
delete the temp node
count --;
// decrease the no.of nodes in the list
return x;
}
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Program:
/*Implement Double Ended Queue using Linked List */
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *previous;
struct node *next;
};
struct node *front, *rear;
int count;
void display();
void insert_begin(int x);
void insert_last(int x);
int delete_begin();
int delete_last();
int main()
{
int ch;
int ele;
printf("\n1. Insert-begin\n2. Insert-last\n3. Delete-begin\n4. Delete-last\n5. Display
\n6.exit");
while(1)
{
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter value for insertion :");
scanf("%d",&ele);
insert_begin(ele);
break;
case 2:
printf(" Enter the value for insertion:");
scanf("%d",&ele);
insert_last(ele);
break;
case 3:
ele = delete_begin();
if(ele!=-1)
printf("%d is deleted .",ele);
break;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
case 4:
ele = delete_last();
if(ele!=-1)
printf("%d is deleted .",ele);
break;
case 5:
display();
break;
case 6: exit(0);
}
}
}
void display()
{
struct node * ptr;
ptr = front;
if(front==NULL || rear==NULL)
{
printf("List is empty");
return;
}
while(ptr != NULL)
{
printf( "%d -> ",ptr ->data);
ptr = ptr->next;
}
printf("\n");;
}
void insert_begin(int x)
{
struct node *new1;
new1 = (struct node*)malloc(sizeof(struct node));
new1 -> data =x;
new1 ->previous = new1 ->next =NULL;
if(front == NULL||rear==NULL)
front = rear = new1;
else
{
new1 ->next = front;
front ->previous = new1;
front = new1;
}
}
void insert_last(int x)
{
struct node *new1;
new1 = (struct node*)malloc(sizeof(struct node));;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
new1 ->data = x;
new1 -> previous = new1 ->next = NULL;
if (front == NULL||rear==NULL)
front = rear = new1;
else
{
rear ->next = new1;
new1 ->previous = rear;
rear = new1;
}
}
int delete_begin()
{
int x;
struct node *temp;
if (front == NULL || rear==NULL)
{
printf( " LIST IS EMPTY ");
return -1;
}
else
{
temp = front;
x= temp->data;
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
{
front = front->next;
front->previous = NULL;
}
count --;
free(temp);
return x;
}
}
int delete_last( )
{
int x;
struct node *temp;
if(rear == NULL || front==NULL)
{
printf( " LIST IS EMPTY ");
return -1;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
else
{
temp = rear;
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
{
rear = rear->previous;
rear -> next = NULL;
}
x= temp ->data;
free(temp);
count --;
return x;
}
}
/*OUTPUT:
1. Insert-begin
2. Insert-last
3. Delete-begin
4. Delete-last
5. Display
6.exit
Enter your choice:1
Enter value for insertion :10
Enter your choice:2
Enter the value for insertion:20
Enter your choice:5
10 -> 20 ->
Enter your choice:1
Enter value for insertion :30
Enter your choice:5
30 -> 10 -> 20 ->
Enter your choice:2
Enter the value for insertion:40
Enter your choice:5
30 -> 10 -> 20 -> 40 ->
Enter your choice:3
Data Structure Lab
30 is deleted .
Enter your choice:5
10 -> 20 -> 40 ->
Enter your choice:4
40 is deleted .
Enter your choice:5
10 -> 20 ->
Enter your choice:6
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 5:Write a C program that uses functions to perform the following:
a) Create a binary search tree of characters.
b) Traverse the above Binary search tree recursively in Postorder.
Definition. A binary search tree (BST) is a binary tree where each node has a Comparable
key (and an associated value) and satisfies the restriction that the key in any node is larger
than the keys in all nodes in that node's left subtree and smaller than the keys in all nodes in
that node's right subtree.
Algorithm
Algorithm: Insert(root, ele)
{
if tree is empty then insert a node as root node otherwise go to next step
if ele is less than the root node the insert left sub tree of root node
otherwise insert right sub tree of root node
}
Algorithm: inorder(struct node *ptr)
{
if(ptr==NULL)
return;
else
{
Visit inorder(ptr->left)
diplay ptr->data
Visit inorder(ptr->right)
}
}
Algorithm: preorder(struct node *ptr)
{
if(ptr==NULL)
return;
else
{
Display ptr->data
Visit preorder(ptr->left)
Visit preorder(ptr->right)
}
}
Algorithm: postorder(ptr)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
if(ptr==NULL)
return;
else
{
Visit postorder(ptr->left);
Visity postorder(ptr->right);
display ptr->data);
}
}
Program
/*BST*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
char data;
struct node *left;
struct node *right;
}*ptr;
struct node *searched,*max,*min;
struct node *deleted(struct node *ptr,char ele);
struct node *insert(struct node *ptr,char ele);
struct node *findmin(struct node *ptr);
struct node *findmax(struct node *ptr);
struct node *search(struct node *ptr,char ele);
void inorder(struct node *ptr);
void preorder(struct node *ptr);
void postorder(struct node *ptr);
void main()
{
int ch;
char ele;
ptr=NULL;
printf("\n ----Main Menu---");
printf("\n1.Insert
\n2.Delete\n3.Search\n4.Inoredr\n5.Preorder\n6.Postorder\n7.Findmin\n8.Findmax\n9.Exit");
while(1)
{
printf("\nEnter ur choice : ");
scanf("%d",&ch);
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
switch(ch)
{
case 1:
printf("\nEnter an element to insert : ");
scanf("\n%c",&ele);
ptr=insert(ptr,ele);
break;
case 2: printf("\nEnter element to delete : ");
scanf("\n%c",&ele);
ptr=deleted(ptr,ele);
printf("\n Deleted Successfully");
break;
case 3: printf("\nEnter a element to search : ");
scanf("\n%c",&ele);
searched=search(ptr,ele);
if(searched==NULL)
printf("\nElement is not found");
else
printf("\nElement is found");
break;
case 4:
inorder(ptr);
break;
case 5: preorder(ptr);
break;
case 6: postorder(ptr);
break;
case 7: min=findmin(ptr);
if(min!=NULL)
printf("\n Minimum value is %c" ,min->data);
else
printf("\nTree is empty");
break;
case 8: max=findmax(ptr);
if(max!=NULL)
printf("\n Maximum value is %c ",max->data);
else
printf("\nTree is empty");
break;
case 9: exit(0);
default: printf("\n Wrong choice");
}
}
}
struct node *insert(struct node *ptr,char ele)
{
if(ptr==NULL)
{
ptr= (struct node *)malloc(sizeof(struct node));
ptr->data=ele;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
ptr->left=ptr->right=NULL;
}
else if(ele<ptr->data)
ptr->left=insert(ptr->left,ele);
else if(ele>ptr->data)
ptr->right=insert(ptr->right,ele);
else
printf("\nElement exists");
return(ptr);
}
struct node *deleted(struct node *ptr,char ele)
{
struct node *tempmin,*temp;
if(ptr==NULL)
{
printf("\nTree is Empty");
return NULL;
}
else if(ele<ptr->data)
ptr->left=deleted(ptr->left,ele);
else if(ele>ptr->data)
ptr->right=deleted(ptr->right,ele);
else
{
if(ptr->left!=NULL && ptr->right!=NULL)
{
tempmin=findmin(ptr->right);
ptr->data=tempmin->data;
ptr->right=deleted(ptr->right,tempmin->data);
free(tempmin);
}
else
{
temp=ptr;
if(ptr->left==NULL)
ptr=ptr->right;
else if(ptr->right==NULL)
{
ptr=ptr->left;
free(temp);
}
}
}
return(ptr);
}
struct node *findmin(struct node *ptr)
{
if(ptr!=NULL)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
while(ptr->left!=NULL)
ptr=ptr->left;
return(ptr);
}
else
return(NULL);
}
struct node *findmax(struct node *ptr)
{
if(ptr!=NULL)
{
while(ptr->right!=NULL)
ptr=ptr->right;
return(ptr);
}
else
return(NULL);
}
struct node *search(struct node *ptr,char ele)
{
if(ptr==NULL)
return NULL;
else
{
if(ele<ptr->data)
return(search(ptr->left,ele));
else if(ele>ptr->data)
return(search(ptr->right,ele));
else if(ele==ptr->data)
return(ptr);
else
return(NULL);
}
}
void inorder(struct node *ptr)
{
if(ptr==NULL)
return;
else
{
inorder(ptr->left);
printf("%c ",ptr->data);
inorder(ptr->right);
}
}
void preorder(struct node *ptr)
{
if(ptr==NULL)
return;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
else
{
printf("%c ",ptr->data);
preorder(ptr->left);
preorder(ptr->right);
}
}
void postorder(struct node *ptr)
{
if(ptr==NULL)
return;
else
{
postorder(ptr->left);
postorder(ptr->right);
printf("%c ",ptr->data);
}
}
/*
OUTPUT:
----Main Menu--1.Insert
2.Delete
3.Search
4.Inoredr
5.Preorder
6.Postorder
7.Findmin
8.Findmax
9.Exit
Enter ur choice : 1
Enter an element to insert : C
Enter ur choice : 1
Enter an element to insert : A
Enter ur choice : 1
Enter an element to insert : B
Enter ur choice : 1
Enter an element to insert : E
Data Structure Lab
Enter ur choice : 1
Enter an element to insert : F
Enter ur choice : 1
Enter an element to insert : D
Enter ur choice : 4
A B C D E F
Enter ur choice : 5
C A B E D F
Enter ur choice : 6
B A D F E C
Enter ur choice : 2
Enter element to delete : C
Deleted Successfully
Enter ur choice : 4
A B D E F
Enter ur choice : 5
D A B E F
Enter ur choice : 6
B A F E D
Enter ur choice : 7
Minimum value is A
Enter ur choice : 8
Maximum value is F
Enter ur choice : 3
Enter a element to search : A
Element is found
Enter ur choice : 9
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 6:Write a C program that uses functions to perform the following:
a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non recursively in inorder.
Algorithm
Algorithm: Insert(root, ele)
{
if tree is empty then insert a node as root node otherwise go to next step
if ele is less than the root node the insert left sub tree of root node
otherwise insert right sub tree of root node
}
Algorithm inorder(ptr)
{
Initially top=-1;
if(ptr==NULL)
return;
else
{
while(ptr!=NULL||top>=0)
{
if(ptr!=NULL)
{
top++;//push the value in stack
stack[top]=ptr;
ptr=ptr->left;
}
else
{
ptr=stack[top];
display ptr->data
top--; //pop the stack
ptr=ptr->right;
}
}
}
}
Program
#include<stdio.h>
#include<stdlib.h>
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
struct node
{
int data;
struct node *left;
struct node *right;
}*ptr;
struct node *searched,*max,*min;
struct node *insert(struct node *ptr,int ele);
struct node *deleted(struct node *ptr,int ele);
struct node *findmin(struct node *ptr);
struct node *findmax(struct node *ptr);
struct node *search(struct node *ptr,int ele);
void inorder(struct node *ptr);
void preorder(struct node *ptr);
void postorder(struct node *ptr);
void main()
{
int ch,ele;
ptr=NULL;
printf("\n ----Main Menu---");
printf("\n1.Insert
\n2.Delete\n3.Search\n4.Inoredr\n5.Preorder\n6.Postorder\n7.Findmin\n8.Findmax\n9.Exit");
while(1)
{
printf("\nEnter ur choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter an elemnet to insert : ");
scanf("%d",&ele);
ptr=insert(ptr,ele);
break;
case 2: printf("\nEnter element to delete : ");
scanf("%d",&ele);
ptr=deleted(ptr,ele);
printf("\n Deleted Successfully");
break;
case 3: printf("\nEnter a element to search : ");
scanf("%d",&ele);
searched=search(ptr,ele);
if(searched==NULL)
printf("\nElement is not found");
else
printf("\nElement is found");
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
break;
case 4:
inorder(ptr);
break;
case 5: preorder(ptr);
break;
case 6: postorder(ptr);
break;
case 7: min=findmin(ptr);
if(min!=NULL)
printf("\n Minimum value is %d",min->data);
else
printf("\nTree is empty");
break;
case 8: max=findmax(ptr);
if(max!=NULL)
printf("\n Maximum value is %d",max->data);
else
printf("\nTree is empty");
break;
case 9: exit(0);
default: printf("\n Wrong choice");
}
}
}
struct node *insert(struct node *ptr,int ele)
{
if(ptr==NULL)
{
ptr=(struct node *)malloc(sizeof(struct node));
ptr->data=ele;
ptr->left=ptr->right=NULL;
}
else if(ele<ptr->data)
ptr->left=insert(ptr->left,ele);
else if(ele>ptr->data)
ptr->right=insert(ptr->right,ele);
else
printf("\nElement exists");
return(ptr);
}
struct node *deleted(struct node *ptr,int ele)
{
struct node *tempmin,*temp;
if(ptr==NULL)
{
printf("\nTree is Empty");
return NULL;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
else if(ele<ptr->data)
ptr->left=deleted(ptr->left,ele);
else if(ele>ptr->data)
ptr->right=deleted(ptr->right,ele);
else
{
if(ptr->left!=NULL && ptr->right!=NULL)
{
tempmin=findmin(ptr->right);
ptr->data=tempmin->data;
ptr->right=deleted(ptr->right,tempmin->data);
free(tempmin);
}
else
{
temp=ptr;
if(ptr->left==NULL)
ptr=ptr->right;
else if(ptr->right==NULL)
{
ptr=ptr->left;
free(temp);
}
}
}
return(ptr);
}
struct node *findmin(struct node *ptr)
{
if(ptr!=NULL)
{
while(ptr->left!=NULL)
ptr=ptr->left;
return(ptr);
}
else
return(NULL);
}
struct node *findmax(struct node *ptr)
{
if(ptr!=NULL)
{
while(ptr->right!=NULL)
ptr=ptr->right;
return(ptr);
}
else
return(NULL);
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
struct node *search(struct node *ptr,int ele)
{
if(ptr==NULL)
return NULL;
else
{
if(ele<ptr->data)
return(search(ptr->left,ele));
else if(ele>ptr->data)
return(search(ptr->right,ele));
else if(ele==ptr->data)
return(ptr);
else
return(NULL);
}
}
void inorder(struct node *ptr)
{
struct node *stack[50];
int top=-1;
if(ptr==NULL)
return;
else
{
while(ptr!=NULL||top>=0)
{
if(ptr!=NULL)
{
top++;
stack[top]=ptr;
ptr=ptr->left;
}
else
{
ptr=stack[top];
printf("%d ",ptr->data);
top--;
ptr=ptr->right;
}
}
}
}
void preorder(struct node *ptr)
{
struct node *stack[50];
int top=-1;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
if(ptr==NULL)
return;
else
{
while(ptr!=NULL||top>=0)
{
if(ptr!=NULL)
{
printf("%d ",ptr->data);
top++;
stack[top]=ptr;
ptr=ptr->left;
}
else
{
ptr=stack[top];
top--;
ptr=ptr->right;
}
}
}
}
void postorder(struct node *ptr)
{
int top=-1,v1=-1;
struct node *stack[25],*s1[25],*ptr1;
if(ptr==NULL)
return;
else
{
stack[++top]=ptr;
while(top>=0)
{
ptr=stack[top--];
s1[++v1]=ptr;
if(ptr->left!=NULL)
stack[++top]=ptr->left;
if(ptr->right!=NULL)
stack[++top]=ptr->right;
}
while(v1!=-1)
{
ptr=s1[v1--];
printf("%d ",ptr->data);
}
}
}
Data Structure Lab
/*
OUTPUT:
----Main Menu--1.Insert
2.Delete
3.Search
4.Inoredr
5.Preorder
6.Postorder
7.Findmin
8.Findmax
9.Exit
Enter ur choice : 1
Enter an elemnet to insert : 5
Enter ur choice : 1
Enter an elemnet to insert : 3
Enter ur choice : 1
Enter an elemnet to insert : 2
Enter ur choice : 1
Enter an elemnet to insert : 4
Enter ur choice : 1
Enter an elemnet to insert : 7
Enter ur choice : 1
Enter an elemnet to insert : 6
Enter ur choice : 1
Enter an elemnet to insert : 8
Enter ur choice : 4
2345678
Enter ur choice : 5
5324768
Enter ur choice : 6
2436875
Enter ur choice : 2
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Enter element to delete : 5
Deleted Successfully
Enter ur choice : 4
234678
Enter ur choice : 5
632478
Enter ur choice : 6
243876
Enter ur choice : 7
Minimum value is 2
Enter ur choice : 8
Maximum value is 8
Enter ur choice : 3
Enter a element to search : 6
Element is found
Enter ur choice : 9
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 7: Write C programs for implementing the following sorting methods to arrange a list
of integers in Ascending order :
a) Insertion sort b) Merge sort
a) Insertion Sort
Example
Algorithm:
Insertion_Sort(a[], n)
{
for(i=1;i<n;j++)
{
k=a[i];
for(j=i-1;j>=0&&k<a[j];j--)
a[j+1]=a[j];
a[j+1]=k;
}
}
Program:
#include<stdio.h>
void Insertion_Sort(int a[],int n);
int main()
{
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
int a[10];
int i,j,temp,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Before Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
Insertion_Sort(a,n);
printf("\nafter Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
}
void Insertion_Sort(int a[],int n)
{
int i,j,k;
for(i=1;i<n;j++)
{
k=a[i];
for(j=i-1;j>=0&&k<a[j];j--)
a[j+1]=a[j];
a[j+1]=k;
}
}
/*OUTPUT:
Enter the no.of elements : 5
Enter a[0] element : 8
Enter a[1] element : 4
Enter a[2] element : 6
Enter a[3] element : 2
Enter a[4] element : 3
Before Sorting array elements are : 8 4 6 2 3
after Sorting array elements are : 2 3 4 6 8
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
b) Merge sort
Example:
Program:
#include<stdio.h>
void Merge_Sort(int a[],int n);
void mpass(int a[],int low,int high);
void msort(int a[],int low,int mid,int high);
int main()
{
int a[10];
int i,j,temp,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Before Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
Merge_Sort(a,n);
printf("\nafter Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
}
void Merge_Sort(int a[],int n)
{
mpass(a,0,n-1);
}
void mpass(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mpass(a,low,mid);
mpass(a,mid+1,high);
msort(a,low,mid,high);
}
}
void msort(int a[],int low,int mid,int high)
{
int n,i,j,k;
int b[20];
n=low;
i=low;
j=mid+1;
while(i<=mid&&j<=high)
{
if(a[i]<=a[j])
{
b[n]=a[i];
i++;
}
else
{
b[n]=a[j];
j++;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
n++;
}
if(i>mid)
{
for(k=j;k<=high;k++)
{
b[n]=a[k];
n++;
}
}
else
{
for(k=i;k<=mid;k++)
{
b[n]=a[k];
n++;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
}
/*OUTPUT:
Enter the no.of elements : 5
Enter a[0] element : 8
Enter a[1] element : 4
Enter a[2] element : 6
Enter a[3] element : 2
Enter a[4] element : 3
Before Sorting array elements are : 8 4 6 2 3
after Sorting array elements are : 2 3 4 6 8
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 8:Write C programs for implementing the following sorting methods to arrange a list
of integers in ascending order:
a) Quick sort b) Selection sort
a) Quick sort
Algorithm:
Quick_Sort(a[],left,right)
{
i=left;
j=right;
pivot=left;
while(i<j)
{
while(a[i]<=a[pivot]&&i<=right)
i++;
while(a[j]>=a[pivot]&&j>left)
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
if(i>j)
{
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
pivot=j;
}
if(left<pivot)
Quick_Sort(a,left,pivot-1);
if(right>pivot)
Quick_Sort(a,pivot+1,right);
}
Program:
#include<stdio.h>
void Quick_Sort(int a[],int left,int right);
int main()
{
int a[10];
int i,j,temp,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
for(i=0;i<n;i++)
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Before Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
Quick_Sort(a,0,n-1);
printf("\nafter Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
}
void Quick_Sort(int a[],int left,int right)
{
int pivot,i,j,temp;
i=left;
j=right;
pivot=left;
while(i<j)
{
while(a[i]<=a[pivot]&&i<=right)
i++;
while(a[j]>=a[pivot]&&j>left)
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
if(i>j)
{
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
pivot=j;
}
if(left<pivot)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Quick_Sort(a,left,pivot-1);
if(right>pivot)
Quick_Sort(a,pivot+1,right);
}
/*OUTPUT:
Enter the no.of elements : 5
Enter a[0] element : 8
Enter a[1] element : 4
Enter a[2] element : 6
Enter a[3] element : 2
Enter a[4] element : 3
Before Sorting array elements are : 8 4 6 2 3
after Sorting array elements are : 2 3 4 6 8
*/
b) Selection sort
Selection Sort procedure with an Example:
Let: a = array containing the values
Let: n = # of elements
1. Find the array element with the min. value among a[0], a[1], ..., a[n-1];
2. Swap this element with a[0]
Illustration:
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Repeat:
1. Find the array element with the min. value among a[1], ..., a[n-1];
2. Swap this element with a[1];
Illustration:
Repeat:
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
1. Find the array element with the min. value among a[2], ..., a[n-1];
2. Swap this element with a[2];
And so on (until we reach the last element in the array)
Algorithm:
Let the values be store in an array "a"
Let n = a.length
for ( i = 0 ; i < n ; i ++ )
{
min=a[i];
for(j=i+1;j<n;j++) //select the min of the rest of array
{
if(min>a[j]) //ascending order for descending reverse
{
minat=j; //the position of the min element
min=a[j];
}
}
2. Swap this element a[min] and a[i]
int temp=a[i] ;
a[i]=a[minat]; //swap
a[minat]=temp;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Program:
#include<stdio.h>
void Selection_Sort(int a[],int n);
int main()
{
int a[10];
int i,j,temp,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Before Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
Selection_Sort(a,n);
printf("\nafter Sorting array elements are : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
}
void Selection_Sort(int a[],int n)
{
int i,j,min,minat;
for(i=0;i<(n-1);i++)
{
minat=i;
min=a[i];
for(j=i+1;j<n;j++) //select the min of the rest of array
{
if(min>a[j]) //ascending order for descending reverse
{
minat=j; //the position of the min element
min=a[j];
}
}
int temp=a[i] ;
a[i]=a[minat]; //swap
a[minat]=temp;
}
}
/*OUTPUT:
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Enter the no.of elements : 5
Enter a[0] element : 8
Enter a[1] element : 4
Enter a[2] element : 6
Enter a[3] element : 2
Enter a[4] element : 3
Before Sorting array elements are : 8 4 6 2 3
after Sorting array elements are : 2 3 4 6 8
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 9:
i. Write a C program to perform the following operation:
a)Insertion into a B-tree.
B-Tree:
A B-tree is an M-way search tree with two special properties:
1. It is perfectly balanced: every leaf node is at the same depth.
2. Every node, except perhaps the root, is at least half-full, i.e. contains M/2 or more
values (of course, it cannot contain more than M-1 values). The root may have any
number of values (1 to M-1).
Example:
5-way B-tree (each node other than the root must contain between 2 and 4 values):
Algorithm:
To insert value X into a B-tree, there are 3 steps:
1. using the SEARCH procedure for M-way trees (described above) find the leaf node to
which X should be added.
2. add X to this node in the appropriate place among the values already there. Being a
leaf node there are no subtrees to worry about.
3. if there are M-1 or fewer values in the node after adding X, then we are finished.
If there are M nodes after adding X, we say the node has overflowed. To repair this,
we split the node into three parts:
Left:
the first (M-1)/2 values
Middle:
the middle value (position 1+((M-1)/2)
Right:
the last (M-1)/2 values
Example:
For example, let's do a sequence of insertions into this B-tree (M=5, so each node other than
the root must contain between 2 and 4 values):
Insert 17: Add it to the middle leaf. No overflow, so we're done.
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Insert 6: Add it to the leftmost leaf. That overflows, so we split it:
 Left = [ 2 3 ]
 Middle = 5
 Right = [ 6 7 ]
Left and Right become nodes; Middle is added to the node above with Left and Right as its
children.
The node above (the root in this small example) does not overflow, so we are done.
Insert 21: Add it to the middle leaf. That overflows, so we split it:
 left = [ 17 21 ]
 Middle = 22
 Right = [ 44 45 ]
Left and Right become nodes; Middle is added to the node above with Left and Right as its
children.
The node above (the root in this small example) does not overflow, so we are done.
Insert 67: Add it to the rightmost leaf. That overflows, so we split it:
 Left = [ 55 66 ]
 Middle = 67
 Right = [ 68 70 ]
Left and Right become nodes; Middle is added to the node above with Left and Right as its
children.
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
But now the node above does overflow. So it is split in exactly the same manner:
 Left = [ 5 10 ] (along with their children)
 Middle = 22
 Right = [ 50 67 ] (along with their children)
Left and Right become nodes, the children of Middle. If this were not the root, Middle would
be added to the node above and the process repeated. If there is no node above, as in this
example, a new root is created with Middle as its only value.
Program:
#include<stdio.h>
#include<stdlib.h>
#define M 5
struct node
{
int n; /* n<M No.of keys in node will always less than order of B-tree */
int keys[M-1]; /*array of keys*/
struct node *p[M]; /* (n+1 pointers will be in use) */
}*root=NULL;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
enum KeyStatus { Duplicate,SearchFailure,Success,InsertIt,LessKeys };
void insert(int key);
void display(struct node *root,int);
void DelNode(int x);
void search(int x);
enum KeyStatus ins(struct node *r, int x, int* y, struct node** u);
int searchPos(int x,int *key_arr, int n);
enum KeyStatus del(struct node *r, int x);
int main()
{
int key;
int choice;
printf("Creation of B tree for order is %d \n",M);
while(1)
{
printf("\n1.Insert\n");
printf("2.Delete\n");
printf("3.Search\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the key : ");
scanf("%d",&key);
insert(key);
break;
case 2:
printf("Enter the key : ");
scanf("%d",&key);
DelNode(key);
break;
case 3:
printf("Enter the key : ");
scanf("%d",&key);
search(key);
break;
case 4:
printf("Btree is :\n");
display(root,10);
break;
case 5:
exit(1);
default:
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
printf("Wrong choice\n");
break;
}
}
return 0;
}
void insert(int key)
{
struct node *newnode;
int upKey;
enum KeyStatus value;
value = ins(root, key, &upKey, &newnode);
if (value == Duplicate)
printf("Key already available\n");
if (value == InsertIt)
{
struct node *uproot = root;
root=(struct node *)malloc(sizeof(struct node));
root->n = 1;
root->keys[0] = upKey;
root->p[0] = uproot;
root->p[1] = newnode;
}
}
enum KeyStatus ins(struct node *ptr, int key, int *upKey,struct node **newnode)
{
struct node *newPtr, *lastPtr;
int pos, i, n,splitPos;
int newKey, lastKey;
enum KeyStatus value;
if (ptr == NULL)
{
*newnode = NULL;
*upKey = key;
return InsertIt;
}
n = ptr->n;
pos = searchPos(key, ptr->keys, n);
if (pos < n && key == ptr->keys[pos])
return Duplicate;
value = ins(ptr->p[pos], key, &newKey, &newPtr);
if (value != InsertIt)
return value;
/*If keys in node is less than M-1 where M is order of B tree*/
if (n < M - 1)
{
pos = searchPos(newKey, ptr->keys, n);
/*Shifting the key and pointer right for inserting the new key*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
for (i=n; i>pos; i--)
{
ptr->keys[i] = ptr->keys[i-1];
ptr->p[i+1] = ptr->p[i];
}
/*Key is inserted at exact location*/
ptr->keys[pos] = newKey;
ptr->p[pos+1] = newPtr;
++ptr->n; /*incrementing the number of keys in node*/
return Success;
}
/*If keys in nodes are maximum and position of node to be inserted is
last*/
if (pos == M - 1)
{
lastKey = newKey;
lastPtr = newPtr;
}
else /*If keys in node are maximum and position of node to be inserted is not last*/
{
lastKey = ptr->keys[M-2];
lastPtr = ptr->p[M-1];
for (i=M-2; i>pos; i--)
{
ptr->keys[i] = ptr->keys[i-1];
ptr->p[i+1] = ptr->p[i];
}
ptr->keys[pos] = newKey;
ptr->p[pos+1] = newPtr;
}
splitPos = (M - 1)/2;
(*upKey) = ptr->keys[splitPos];
(*newnode)= (struct node *)malloc(sizeof(struct node)); /*Right node after split*/
ptr->n = splitPos;
/*No. of keys for left splitted node*/
(*newnode)->n = M-1-splitPos;
/*No. of keys for right splitted node*/
for (i=0; i < (*newnode)->n; i++)
{
(*newnode)->p[i] = ptr->p[i + splitPos + 1];
if(i < (*newnode)->n - 1)
(*newnode)->keys[i] = ptr->keys[i + splitPos + 1];
else
(*newnode)->keys[i] = lastKey;
}
(*newnode)->p[(*newnode)->n] = lastPtr;
return InsertIt;
}
void display(struct node *ptr, int blanks)
{
if (ptr)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
int i;
for(i=1;i<=blanks;i++)
printf(" ");
for (i=0; i < ptr->n; i++)
printf("%d ",ptr->keys[i]);
if(blanks==10)
printf("\n");
for (i=0; i <= ptr->n; i++)
display(ptr->p[i], blanks-5);
}
}
void search(int key)
{
int pos, i, n;
struct node *ptr = root;
printf("Search path:\n");
while (ptr)
{
n = ptr->n;
for (i=0; i < ptr->n; i++)
printf("%d ",ptr->keys[i]);
printf("\n");
pos = searchPos(key, ptr->keys, n);
if (pos < n && key == ptr->keys[pos])
{
printf("Key
%d
found
dispalyednode\n",key,pos);
return;
}
ptr = ptr->p[pos];
}
printf("Key %d is not available\n",key);
}
int searchPos(int key, int *key_arr, int n)
{
int pos=0;
while (pos<n && key>key_arr[pos])
pos++;
return pos;
}
void DelNode(int key)
{
struct node *uproot;
enum KeyStatus value;
value = del(root,key);
switch (value)
in
position
%d
of
last
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
case SearchFailure:
printf("Key %d is not available\n",key);
break;
case LessKeys:
uproot = root;
root = root->p[0];
free(uproot);
break;
}
}
enum KeyStatus del(struct node *ptr, int key)
{
int pos, i, pivot, n ,min;
int *key_arr;
enum KeyStatus value;
struct node **p,*lptr,*rptr;
if (ptr == NULL)
return SearchFailure;
/*Assigns values of node*/
n=ptr->n;
key_arr = ptr->keys;
p = ptr->p;
min = (M - 1)/2;
/*Minimum number of keys*/
pos = searchPos(key, key_arr, n);
if (p[0]==NULL)
{
if (pos==n || key<key_arr[pos])
return SearchFailure;
/*Shift keys and pointers left*/
for (i=pos+1; i<n; i++)
{
key_arr[i-1] = key_arr[i];
p[i] = p[i+1];
}
return --ptr->n >= (ptr==root ? 1 : min) ? Success : LessKeys;
}
if(pos<n && key==key_arr[pos])
{
struct node *qp = p[pos], *qp1;
int nkey;
while(1)
{
nkey = qp->n;
qp1 = qp->p[nkey];
if (qp1 == NULL)
break;
qp = qp1;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
key_arr[pos] = qp->keys[nkey-1];
qp->keys[nkey - 1] = key;
}
value = del(p[pos], key);
if (value != LessKeys)
return value;
if (pos > 0 && p[pos-1]->n > min)
{
pivot = pos - 1; /*pivot for left and right node*/
lptr = p[pivot];
rptr = p[pos];
/*Assigns values for right node*/
rptr->p[rptr->n + 1] = rptr->p[rptr->n];
for (i=rptr->n; i>0; i--)
{
rptr->keys[i] = rptr->keys[i-1];
rptr->p[i] = rptr->p[i-1];
}
rptr->n++;
rptr->keys[0] = key_arr[pivot];
rptr->p[0] = lptr->p[lptr->n];
key_arr[pivot] = lptr->keys[--lptr->n];
return Success;
}
if (pos > min)
{
pivot = pos; /*pivot for left and right node*/
lptr = p[pivot];
rptr = p[pivot+1];
/*Assigns values for left node*/
lptr->keys[lptr->n] = key_arr[pivot];
lptr->p[lptr->n + 1] = rptr->p[0];
key_arr[pivot] = rptr->keys[0];
lptr->n++;
rptr->n--;
for (i=0; i < rptr->n; i++)
{
rptr->keys[i] = rptr->keys[i+1];
rptr->p[i] = rptr->p[i+1];
}
rptr->p[rptr->n] = rptr->p[rptr->n + 1];
return Success;
}
if(pos == n)
pivot = pos-1;
else
pivot = pos;
lptr = p[pivot];
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
rptr = p[pivot+1];
/*merge right node with left node*/
lptr->keys[lptr->n] = key_arr[pivot];
lptr->p[lptr->n + 1] = rptr->p[0];
for (i=0; i < rptr->n; i++)
{
lptr->keys[lptr->n + 1 + i] = rptr->keys[i];
lptr->p[lptr->n + 2 + i] = rptr->p[i+1];
}
lptr->n = lptr->n + rptr->n +1;
free(rptr); /*Remove right node*/
for (i=pos+1; i < n; i++)
{
key_arr[i-1] = key_arr[i];
p[i] = p[i+1];
}
return --ptr->n >= (ptr==root ? 1 : min) ? Success : LessKeys;
}
/*
OUTPUT:
Creation of B tree for order is 5
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 1
Enter the key : 1
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 1
Enter the key : 2
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 1
Enter the key : 3
1.Insert
2.Delete
Data Structure Lab
3.Search
4.Display
5.Quit
Enter your choice : 1
Enter the key : 4
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice :4
Btree is :
1 2 3 4
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 1
Enter the key : 5
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 4
Btree is :
3
1 2
4 5
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice :2
Enter the key : 5
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 4
Btree is :
1 2 3 4
1.Insert
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 3
Enter the key : 5
Search path:
1234
Key 5 is not available
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice : 3
Enter the key : 1
Search path:
1234
Key 1found in position 0 of last dispalyednode
1.Insert
2.Delete
3.Search
4.Display
5.Quit
Enter your choice :5
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
ii.
Write a C program for implementing Heap sort algorithm for sorting a given list
of integers in ascending order.
Example:
Apply the Heap sort for the following Heap tree:
Apply the Heap sort procedure:
The last value of 5
is no longer in the
heap.
Now let the new
value at the root
percolate down to
where it belongs.
Now repeat with
the new root value
(just chance it is 5
again):
And keep continuing:
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Program:
//c program to implement heap sort
#include<stdio.h>
void adjust(int a[],int i,int n);
void heapify(int a[],int n);
void heapsort(int a[],int n);
//BEGIN MAIN
void main()
{
int n,a[10],i;
printf("enter size of an array");
scanf("%d",&n);
printf("enter elements");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
heapsort(a,n);
printf("the elements in sorted order are:\n");
for(i=1;i<=n;i++)
{
printf("-> %d ",a[i]);
}
}//END OF MAIN
//implementation of function adjust
void adjust(int a[],int i,int n)
{
int j=2*i;
int item=a[i];
while(j<=n)
{
if((j<n)&&(a[j]<a[j+1]))
++j;
if(item>=a[j])
break;
else
{
a[j/2]=a[j];
j=2*j;
}
}
a[j/2]=item;
}
//implementation of function heapify
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
void heapify(int a[],int n)
{
int i;
for(i=n/2;i>=1;i--)
adjust(a,i,n);
}
//implementation of HEAPSORT
void heapsort(int a[],int n)
{
int i;
heapify(a,n);
for(i=n;i>=2;i--)
{
int temp=a[i];
a[i]=a[1];
a[1]=temp;
adjust(a,1,i-1);
}
}
/*
OUPUT:
enter size of an array5
enter elements25
36
14
26
21
the elements in sorted order are:
-> 14 -> 21 -> 25 -> 26 -> 36
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 10: Write a C program to implement all the functions of a dictionary (ADT) using
hashing.
AIM : Write a C++ program to implement all the functions of a dictionary (ADT) using
hashing.
Dictionary : A Dictionary is a collection of pairs of the form (K,V). where ‘K’ is a Key and
‘V’ is the value associated with the key ‘k’. No two pairs in the dictionary have a same key.
The Following operations performed on a dictionary :
 Determine whether or not the dictionary is empty
 Determine the dictionary Size ( No of Pairs )
 Find the pair with a specified key
 Insert a pair into the dictionary
 Delete or erase the pair into the specified key
ABSTRACT DATA TYPE :
INSTANCES : Collection of pairs with distinct keys
OPERATIONS :
 Empty() : return true iff the dictionary is empty
 Size() : return the no. of pairs in the dictionary
 Find(k) : return the pair with the key , K.
 Insert(p) : insert the pair ‘P’ into the dictionary
 Erase(k) : delete the pair with key ‘K’.
Program:
#include<stdio.h>
#include<stdlib.h>
int a[50];
int deviser;
void hashinitialize();
void insert(int);
void delet(int);
void disp();
int find(int);
int full();
void main()
{
int ch,ele,y;
hashinitialize();
printf("\n1.insert:");
printf("\n2.del:");
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
printf("\n3.find:");
printf("\n4.disp:");
printf("\n5.exit:");
do
{
printf("\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nEnter the element:");
scanf("%d",&ele);
insert(ele);
break;
case 2:printf("\nEnter the element to delete:");
scanf("%d",&ele);
delet(ele);
break;
case 3:printf("\nEnter the element to find:");
scanf("%d",&ele);
y=find(ele);
if(y==-1)
{
printf("Element not found");
}
else
{
printf("Element found at %d Position",y+1);
}
break;
case 4: printf("\nThe elements are:");
disp();
break;
case 5:exit(0);
break;
default: printf("wrong choice");
}
}while(1);
}
void hashinitialize()
{
int i;
printf("\n enter the deviser:");
scanf("%d",&deviser);
for(i=0;i<deviser;i++)
a[i]=-1;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
int full()
{
int i;
for(i=0;i<deviser;i++)
{
if(a[i]==-1)return 0;
}
return 1;
}
void disp()
{
int i;
for(i=0;i<deviser;i++)
{
if(a[i]==-1)
{
printf(" -1 ");
}
else
{
printf("%d ",a[i]);
}
}
}
void insert(int x)
{
int i,j,k;
i=find(x);
if(full())
{
printf("Hash table is full,we cannot insert");
return;
}
else if(i>=0)
{
printf("\n It is a duplicate element\n");
return;
}
else
{
k=x%deviser;
for(j=0;j<deviser;j++)
{
if(a[k]==-1)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
a[k]=x;
printf("Element inserted");
return;
}
else
{
if(k==(deviser-1))
k=0;
else
k++;
}
}
}
}
void delet(int x)
{
int i;
i=find(x);
if(i==-1)
{
printf("\nElement not found\n");
return;
}
else
{
a[i]=-1;
printf("Element deleted");
}
}
int find(int x)
{
int i,j;
i=x%deviser;
for(j=0;j<deviser;j++)
{
if(a[i]==x)
return i;
else
{
if(i==(deviser-1))
i=0;
else
i++;
}
}
Data Structure Lab
return -1;
}
/*
OUTPUT:
enter the deviser:10
1.insert:
2.del:
3.find:
4.disp:
5.exit:
Enter the choice:1
Enter the element:45
Element inserted
Enter the choice:1
Enter the element:86
Element inserted
Enter the choice:1
Enter the element:56
Element inserted
Enter the choice:1
Enter the element:85
Element inserted
Enter the choice:1
Enter the element:72
Element inserted
Enter the choice:1
Enter the element:32
Element inserted
Enter the choice:1
Enter the element:44
Element inserted
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Enter the choice:1
Enter the element:36
Element inserted
Enter the choice:1
Enter the element:25
Element inserted
Enter the choice:1
Enter the element:43
Element inserted
Enter the choice:1
Enter the element:85
Hash table is full,we cannot insert
Enter the choice:4
The elements are:25 43 72 32 44 45 86 56 85 36
Enter the choice:3
Enter the element to find:25
Element found at 1 Position
Enter the choice:4
The elements are:25 43 72 32 44 45 86 56 85 36
Enter the choice:2
Enter the element to delete:25
Element deleted
Enter the choice:3
Enter the element to find:25
Element not found
Enter the choice:5
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 11: Write a C program for implementing Knuth-Morris- Pratt pattern matching
algorithm.
Algorithm:
ALGORITHM :
1.
2.
3.
4.
f = failure (p)
j=0
i=0
Repeat the following steps while i<n
if p[i] = T[i] then
if j = m-1 then returns i-m+1 and
i = i+1 ; j = j+1
else if (j>0) then j = f [j-1]
5. else
i = i+1
6. return – 1
Failure function :
1. f[0] = 0
2. j = 0
3. i = 1
4. while (i<m) do
if p[i] = = p[j] then f[i] = j+1 , i = i+1 , j = j+1
else if j>0 then j = f[j-1]
else f[i] = 0 ; i =i+1
Program:
/* KMP pattern matching */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char T[20],P[20];
int fail[10];
void read();
int KMPMatch(char T[],char P[],int fail[]);
void main()
{
int n;
read();
n=KMPMatch(T,P,fail);
if(n==-1)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
printf("Pattern is not matched");
}
else
{
printf("Pattern is matched from the position : %d ",n);
}
}
void read()
{
printf("Enter main string : ");
//scanf("%s",T);
gets(T);
printf("Enter sub string : ");
//scanf("%s",P);
gets(P);
}
void failure(char p[ ])
{
int i, j, m, n;
f [0] = 0;
j = 0;
i = 1;
while(i<n)
{
if (p[i] = = p[j])
{
f [i] = j+1;
i++;
j++;
}
else
if (j>0)
j = f [j-1];
else
{
f[i] = 0;
i++;
}
}
}
int KMPMatch(char T[],char P[],int fail[])
{
int n=strlen(T);
int m=strlen(P);
// failure (p);
int i=0;
int j=0;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
while(i<n)
{
if(T[i]==P[j])
{
if(j==m-1)
{
return(i-m+1);
}
else
{
i++;
j++;
}
}
else
{
if(j>0)
j=fail[j-1];
else
i++;
}
}
return(-1);
}
/*
OUTPUT:
Enter main string : hello how are you
Enter sub string : are
Pattern is matched from the position : 10
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Week 12: Write C programs for implementing the following graph traversal algorithms:
a)Depth first traversal
b)Breadth first traversal
AIM : To implement BFS and DFS and perform operations on them .
GRAPH TRAVERSAL:
A traversal is a systematic procedure for exploring a graph by examining
all of its vertices and edges. A traversal is efficient if it visits all the vertices and edges in
time proportional to their number, that is in linear time.
TYPES OF TRAVERSALS :
There are 2 types of traversals
1. Breadth first traversal (BFS)
2. Depth first traversal (DFS)
BFS :
All the adjacent nodes of a vertex are processed before going to next level i.e the level
‘0’ vertices are processed before level ‘1’. And level ‘1’ are processed before level 2 i.e in
general level (n-1) vertices are processed before level ‘n’.
STEPS FOR BFS :
1.We begin by enqueing the starting vertex A .
2.We then loop by dequeing the queue from the front end of the queue. After processing a
vertex , place all the adjacent vertices in the queue .
3.when the queue is empty, the traversal is completed .
DFS:
In this all of nodes descendents are visited before we move to an adjacent nodes. The
adjacent nodes are processed using ‘LIFO’.
1. Traversal starts at ‘A’. Push it into stack.
2. When we loop and pop the stack after processing the vertex , push all the adjacent vertices
into the stack .
3. To process ‘B’ at step-2 we push onto the stack C,D,E before processing either G (or) F .
4. If when the stack is empty , the traversal is completed .
a)Depth first traversal
#include<stdio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
int main()
{
int m;
printf("enterno of vertices");
scanf("%d",&n);
printf("ente no of edges");
scanf("%d", &m);
printf("\nEDGES \n");
for(k=1;k<=m;k++)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
scanf("%d%d",&i,&j);
cost[i][j]=1;
}
printf("enter initial vertex");
scanf("%d",&v);
printf("ORDER OF VISITED VERTICES");
printf( "%d ",v);
visited[v]=1;
k=1;
while(k<n)
{
for(j=n;j>=1;j--)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
}
v=stk[--top];
printf( "%d ",v);
k++;
visit[v]=0;
visited[v]=1;
}
}
/*
OUTPUT:
enterno of vertices 6
ente no of edges 8
EDGES
12
13
14
15
26
36
46
56
enter initial vertex 1
ORDER OF VISITED VERTICES 1 2 6 3 4 5
*/
b)Breadth first traversal
#include<stdio.h>
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
#include<stdlib.h>
int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10];
int main()
{
int m;
printf("enterno of vertices");
scanf("%d",&n);
printf("ente no of edges");
scanf("%d",&m);
printf("\nEDGES \n");
for(k=1;k<=m;k++)
{
scanf("%d%d",&i,&j);
cost[i][j]=1;
}
printf("enter initial vertex");
scanf("%d",&v);
printf("Visitied vertices\n");
printf("%d ",v);
visited[v]=1;
k=1;
while(k<n)
{
for(j=1;j<=n;j++)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
qu[rare++]=j;
}
v=qu[front++];
printf("%d ",v);
k++;
visit[v]=0; visited[v]=1;
}
}
/*
OUTPUT:
enterno of vertices7
ente no of edges9
EDGES
12
13
14
15
Data Structure Lab
26
67
37
47
57
enter initial vertex1
Visitied vertices
1 2 3 4 5 6 7
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
Additional Programs
13) Implement a Stack using arrays
14) Implement a Stack using Linked List
15) Implement a Queue using arrays
16) Implement a Queue using Linked List
17) Implement a Circular Queue
18) Evaluate a Post fix Expression using stack
19) Implement Linear hashing Technique
20) Implement a sparse matrix using arrays
21) Implement a Linear Search with Recursive
22) Implement a Linear Search with Non Recursive
23) Implement a Binary Search with Recursive
24) Implement a Binary Search with Non Recursive
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
1) Implement a Stack using arrays
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 4
int stack[MAXSIZE],top=-1,i;
void push();
void pop();
void display();
void peek();
int main()
{
int ch;
do
{
printf("\n 1.push\n 2.pop\n 3.display\n 4.peek\n 5.exit\n");
printf("\n enter your choice[1-5]:");
scanf("%d",&ch);
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4: peek();
break;
case 5: exit(0);
default:printf("\n invalid option");
}
}while(1);
}
/*Insert an element at top of the stack*/
void push()
{
int ele;
if(top==MAXSIZE-1)
{
printf("\n stack is full(overflow)\n");
return;
}
else
{
printf("enter the element to push:");
scanf("%d",&ele);
top++;
stack[top]=ele;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
/*delete the top element of the stack*/
void pop()
{
if(top==-1)
{
printf("\n stack is empty(underflow)\n");
return;
}
else
{
printf("the pop element is:%d",stack[top]);
top--;
}
}
/*Display all elements of stack in LIFO format(Last In First out)*/
void display()
{
if(top==-1)
{
printf("\n stack is empty(underflow)");
return;
}
else
{
printf("\n the elements in stack are:\n");
for(i=top;i>=0;i--)
printf("->%d",stack[i]);
}
}
/*display the top element of the stack*/
void peek()
{
if(top==-1)
{
printf("\n stack is empty(underflow)");
return;
}
else
printf("->%d",stack[top]);
}
/*OUTPUT:
* [mm0528@agni DS]$ cc stackarray.c
[mm0528@agni DS]$ ./a.out
1.push
2.pop
Data Structure Lab
3.display
4.peek
5.exit
enter your choice[1-5]:1
enter the element to push:10
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:1
enter the element to push:20
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:3
the elements in stack are:
->20->10
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:1
enter the element to push:40
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:3
the elements in stack are:
->40->20->10
1.push
2.pop
3.display
4.peek
5.exit
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
enter your choice[1-5]:4
->40
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:2
the pop element is:40
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:3
the elements in stack are:
->20->10
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:2
the pop element is:20
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:2
the pop element is:10
1.push
2.pop
3.display
4.peek
5.exit
enter your choice[1-5]:2
stack is empty(underflow)
1.push
2.pop
3.display
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
4.peek
5.exit
enter your choice[1-5]:5
[mm0528@agni DS]$
*
* */
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
2) Implement a stack using Linked List
#include<stdlib.h>
#include<stdio.h>
void push();
void pop();
void display();
struct node
{
int data;
struct node*next;
};
struct node*top=NULL;
main()
{
int ch;
while(1)
{
printf("\n 1.push\n 2.pop\n 3.display\n 4.quit\n");
printf("enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:exit(0);
default:printf("\n wrong choice \n");
}
}
}
void push()
{
struct node*temp;
int item;
temp=(struct node*)malloc(sizeof(struct node));
printf("\n enter data of item:");
scanf("%d",&item);
temp->data=item;
temp->next=top;
top=temp;
}
void pop()
{
struct node*temp;
if(top==NULL)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
printf("\n stack is empty \n");
else
{
temp=top;
printf("popped item is %d \n",temp->data);
top=top->next;
free(temp);
}
}
void display()
{
struct node*new1;
new1=top;
if(top==NULL)
printf("stack is empty \n");
else
{
printf("stack elements:\n");
while(new1!=NULL)
{
printf("->%d",new1->data);
new1=new1->next;
}
}
}
/*
OUTPUT:
1.push
2.pop
3.display
4.quit
enter your choice:1
enter data of item:10
1.push
2.pop
3.display
4.quit
enter your choice:1
enter data of item:20
1.push
2.pop
3.display
Data Structure Lab
4.quit
enter your choice:3
stack elements:
->20->10
1.push
2.pop
3.display
4.quit
enter your choice:1
enter data of item:30
1.push
2.pop
3.display
4.quit
enter your choice:3
stack elements:
->30->20->10
1.push
2.pop
3.display
4.quit
enter your choice:2
popped item is 30
1.push
2.pop
3.display
4.quit
enter your choice:3
stack elements:
->20->10
1.push
2.pop
3.display
4.quit
enter your choice:2
popped item is 20
1.push
2.pop
3.display
4.quit
enter your choice:3
stack elements:
->10
1.push
2.pop
3.display
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
4.quit
enter your choice:2
popped item is 10
1.push
2.pop
3.display
4.quit
enter your choice:3
stack is empty
1.push
2.pop
3.display
4.quit
enter your choice:4
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
3) Impement a Queue Using arrays
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 4
int Queue[MAXSIZE],front=-1,rear=-1,i;
void enqueue();
void dequeue();
void display();
int main()
{
int ch;
do
{
printf("\n 1.ENQUEUE\n 2.DEQUEUE\n 3.DISPLAY\n 4.EXIT\n");
printf("enter your choice[1-4]:");
scanf("%d",&ch);
switch(ch)
{
case 1:enqueue();
break;
case 2:dequeue();
break;
case 3:display();
break;
case 4:exit(0);
default:printf("invalid option \n");
}
}while(1);
}
void enqueue()
{
if(rear==MAXSIZE-1)
{
printf("queue is full(overflow)\n");
return;
}
rear++;
printf("enter the element to ENQUEUE:\n");
scanf("%d",&Queue[rear]);
if(front==-1)
front++;
}
void dequeue()
{
if(front==-1)
{
printf("queue is empty(underflow)\n");
return;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
printf("the DEQUEUE element is:%d \n",Queue[front]);
if(front==rear)
front=rear=-1;
else
front++;
}
void display()
{
if(front==-1)
{
printf("queue is empty(underflow)\n");
return;
}
printf("the element in queue are:front->");
for(i=front;i<=rear;i++)
printf("%d ",Queue[i]);
printf("<-REAR\n");
}
/*OUTPUT:
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:1
enter the element to ENQUEUE:
10
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:1
enter the element to ENQUEUE:
20
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:1
enter the element to ENQUEUE:
30
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
enter your choice[1-4]:3
the element in queue are:front->10 20 30 <-REAR
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:2
the DEQUEUE element is:10
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:3
the element in queue are:front->20 30 <-REAR
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:2
the DEQUEUE element is:20
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:3
the element in queue are:front->30 <-REAR
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:2
the DEQUEUE element is:30
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:3
queue is empty(underflow)
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:2
Data Structure Lab
queue is empty(underflow)
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
enter your choice[1-4]:4
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
4)Implement a Queue using linked list
#include<stdlib.h>
#include<stdio.h>
struct node
{
int data;
struct node*next;
};
struct node*front=NULL,*rear=NULL;
void enqueue();
void dequeue();
void display();
void main()
{
int ch;
while(1)
{
printf("\n 1.insert\n 2.delete\n 3.display\n 4.exit\n");
printf("\n enter ur choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:enqueue();
break;
case 2:dequeue();
break;
case 3:display();
break;
case 4:exit(0);
default:printf("\n invalid option");
}
}
}
void enqueue()
{
int ele;
struct node*temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("\n enter the element to be inserted");
scanf("%d",&ele);
temp->data=ele;
temp->next=NULL;
if(rear==NULL||front==NULL)
front=temp;
else
rear->next=temp;
rear=temp;
}
void dequeue()
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
{
struct node*temp;
if(front==NULL||rear==NULL)
printf("\n queue underflow");
else
{
temp=front;
printf("\n deleted element is %d",temp->data);
front=front->next;
free(temp);
}
}
void display()
{
struct node*temp;
temp=front;
if(front==NULL||rear==NULL)
printf("\n queue is empty");
else
{
printf("\n front");
while(temp!=NULL)
{
printf("->%d",temp->data);
temp=temp->next;
}
printf("->rear \n");
}
}
/*OUTPUT:
1.insert
2.delete
3.display
4.exit
enter ur choice:1
enter the element to be inserted10
1.insert
2.delete
3.display
4.exit
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
enter ur choice:1
enter the element to be inserted20
1.insert
2.delete
3.display
4.exit
enter ur choice:1
enter the element to be inserted30
1.insert
2.delete
3.display
4.exit
enter ur choice:3
front->10->20->30->rear
1.insert
2.delete
3.display
4.exit
enter ur choice:2
deleted element is 10
1.insert
2.delete
3.display
4.exit
enter ur choice:3
front->20->30->rear
1.insert
2.delete
3.display
4.exit
enter ur choice:2
deleted element is 20
1.insert
2.delete
3.display
Data Structure Lab
4.exit
enter ur choice:3
front->30->rear
1.insert
2.delete
3.display
4.exit
enter ur choice:2
deleted element is 30
1.insert
2.delete
3.display
4.exit
enter ur choice:3
queue is empty
1.insert
2.delete
3.display
4.exit
enter ur choice:4
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
5) Implement Circular Queue
#include<stdio.h>
#define max 5
int front,rear,q[max];
void enqueue(void);
void dequeue(void);
void qdisplay(void);
void main(void)
{
int c;
clrscr();
front=rear=-1;
do
{
printf("1:insert\n2:deletion\n3:display\n4:exit\nenter choice:");
scanf("%d",&c);
switch(c)
{
case 1:enqueue();break;
case 2:dequeue();break;
case 3:qdisplay();break;
case 4:printf("pgm ends\n");break;
default:printf("wrong choice\n");break;
}
}while(c!=4);
getch();
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
void enqueue(void)
{
int x;
if((front==0&&rear==max-1)||(front==rear+1))
{
printf("Queue is overflow\n");return;
}
if(front==-1)
{
front=rear=0;
}
else
{
if(rear==max-1)
{
rear=0;
}
else
{
rear++;
}
}
printf("enter the no:\n");
scanf("%d",&x);
q[rear]=x;
printf("%d succ. inserted\n",x);
return;
//condition for full Queue
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
void dequeue(void)
{
int y;
if(front==-1)
{
printf("q is underflow\n");return;
}
y=q[front];
if(front==rear)
{
front=rear=-1;
}
else
{
if(front==max-1)
{
front=0;
}
else
{
front++;
}
}
printf("%d succ. deleted\n",y);
return;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
void qdisplay(void)
{
int i,j;
if(front==rear==-1)
{
printf("q is empty\n");return;
}
printf("elements are :\n");
for(i=front;i!=rear;i=(i+1)%max)
{
printf("%d\n",q[i]);
}
printf("%d\n",q[rear]);
return;
}
/*
OUTPUT
1:insert
2:deletion
3:display
4:exit
enter choice:1
enter the no:
Data Structure Lab
10
10 succ. inserted
1:insert
2:deletion
3:display
4:exit
enter choice:1
enter the no:
20
20 succ. inserted
1:insert
2:deletion
3:display
4:exit
enter choice:1
enter the no:
30
30 succ. inserted
1:insert
2:deletion
3:display
4:exit
enter choice:1
enter the no:
40
40 succ. inserted
1:insert
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
2:deletion
3:display
4:exit
enter choice:1
enter the no:
50
50 succ. inserted
1:insert
2:deletion
3:display
4:exit
enter choice:1
Queue is overflow
1:insert
2:deletion
3:display
4:exit
enter choice:3
elements are :
10
20
30
40
50
1:insert
2:deletion
3:display
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
4:exit
enter choice:2
10 succ. deleted
1:insert
2:deletion
3:display
4:exit
enter choice:1
enter the no:
60
60 succ. inserted
1:insert
2:deletion
3:display
4:exit
enter choice:3
elements are :
20
30
40
50
60
1:insert
2:deletion
3:display
4:exit
enter choice:4
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
6) Evaluation of Postfix expression
1.
2.
3.
4.
5.
Algorithm:
operand_stack = empty stack
while (not end of input)
symbol = next input symbol
if (symbol is operand)
push(operand_stack, symbol)
end if
else
operand2 = pop(operand_stack)
operand1 = pop(operand_stack)
result = apply symbol to operand1 and operand2
push(operand_stack, result)
end else
return pop(operand_stack)
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
7) Implement a Linear Probing
#include<stdio.h>
int a[10];
int num;
int key;
void linearprobe();
void lineardisp();
void main()
{
printf("elements in lineararatic probing--\n");
linearprobe();
lineardisp();
} // end of the program
void linearprobe()
{
int i,j,count=1;
for(i=0;i<10;i++)
a[i]=0;
printf("enter 10 elements only, if exceed 10 elements automatically end(1)\n");
while(count<=10)
/* reading elements */
{
printf("insert element (-1 to stop)");
scanf("%d",&num);
if(num==-1)
return;
key=num%10;
if(a[key]==0)
a[key]=num;
else
{
/* placing the elements */
i=1;
j=key;
while(a[j]!=0)
{
j=(key+i)%10;
i=i+1;
}
if(a[j]==0)
a[j]=num;
}
count++;
}
printf("array size is Completed");
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
void lineardisp()
/* displaying elements */
{
int i;
printf("\nAfter arranging the Linear Probing elements are:");
for(i=0;i<10;i++)
printf("%d ",a[i]);
printf("\n");
}
/*
elements in lineararatic probing-enter 10 elements only, if exceed 10 elements automatically end(-1)
insert element (-1 to stop)52
insert element (-1 to stop)15
insert element (-1 to stop)14
insert element (-1 to stop)26
insert element (-1 to stop)35
insert element (-1 to stop)63
insert element (-1 to stop)42
insert element (-1 to stop)-1
After arranging the Linear Probing elements are:0 0 52 63 14 15 26 35 42 0
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
8) Implement Sparse Matrix
#include<stdio.h>
int spa[10][10];
void spmatrix(int,int,int);
void main()
{ int i,j,n,m,num,elem=0;
printf("\nenter no. of rows: ");
scanf("%d",&n);
printf("\nenter no. of column: ");
scanf("%d",&m);
printf("\nenter the elements of array\n");
for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{ scanf("%d",&spa[i][j]);
}
}
printf("\nmatrix:\n");
for(i=0;i<n;i++)
{for(j=0;j<m;j++)
{ printf(" %d",spa[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{ if(spa[i][j]!=0)
elem++;
}
}
spmatrix(elem+1,n,m);
}
void spmatrix(int t,int n,int m)
{ int b[10][3],i,j,q=1;
b[0][0]=n;
b[0][1]=m;
b[0][2]=t-1;
for(i=1;i<=n;i++)
{for(j=1;j<=m;j++)
{ if(spa[i-1][j-1]!=0)
{ b[q][0]=i;
b[q][1]=j;
b[q][2]=spa[i-1][j-1];
q++;
}
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
}
printf("\n\nsparse matrix:\n");
for(i=0;i<t;i++)
{for(j=0;j<3;j++)
{ printf(" %d",b[i][j]);
}
printf("\n");
}
}
/*
OUTPUT:
enter no. of rows: 3
enter no. of column: 3
enter the elements of array
1
0
2
0
3
4
0
1
0
matrix:
102
034
010
sparse matrix:
cloumn number - row number - data 3 3 5
111
132
223
234
321
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
9)Implemenet a Linear Search with Recursive
#include<stdio.h>
int linear_search(int a[],int n,int key);
int main()
{
int a[10];
int i,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Enter searching element : ");
scanf("%d",&key);
if(linear_search(a,n,key)!=-1)
printf("%d is found",key);
else
printf("%d is not found",key);
}
int linear_search(int a[],int n,int key)
{
if( a[n] == key)
{
return n;
}
else if((n==0))
{
return -1;
}
else
{
return(linear_search(a,n-1,key));
}
}
/*output 1:
[mm0528@agni DS]$ cc Linear_SearchNR.c
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 2
Enter a[1] element : 4
Enter a[2] element : 1
Data Structure Lab
Enter a[3] element : 6
Enter a[4] element : 3
Enter searching element : 7
7 is not found
output 2 :
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 4
Enter a[1] element : 6
Enter a[2] element : 1
Enter a[3] element : 3
Enter a[4] element : 2
Enter searching element : 3
3 is found
[mm0528@agni DS]$
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
10)Implement a Linear Search with Non recursive
#include<stdio.h>
int linear_search(int a[],int n,int key);
int main()
{
int a[10];
int i,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Enter searching element : ");
scanf("%d",&key);
if(linear_search(a,n,key)!=-1)
printf("%d is found",key);
else
printf("%d is not found",key);
}
int linear_search(int a[],int n,int key)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==key)
return(key);
}
return(-1);
}
/*output 1:
[mm0528@agni DS]$ cc Linear_SearchNR.c
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 2
Enter a[1] element : 4
Enter a[2] element : 1
Enter a[3] element : 6
Enter a[4] element : 3
Enter searching element : 7
7 is not found
Data Structure Lab
output 2 :
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 4
Enter a[1] element : 6
Enter a[2] element : 1
Enter a[3] element :
3
Enter a[4] element : 2
Enter searching element : 3
3 is found
[mm0528@agni DS]$
*/
Marri Lakshman Reddy Institute of Technology and management
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
11)Implement a Binary Search with Recursive
#include<stdio.h>
int Binary_search(int a[],int low,int high,int key);
int main()
{
int a[10];
int i,j,temp,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Enter searching element : ");
scanf("%d",&key);
/* sorting process */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(Binary_search(a,0,n-1,key)!=-1)
printf("%d is found",key);
else
printf("%d is not found",key);
}
int Binary_search(int a[],int low,int high,int key)
{
int n,mid,i,j,temp;
n=high+1;
if(low<=high)
{
mid=(low+high)/2;
if(a[mid]>key)
return(Binary_search(a,low,mid-1,key));
else if(a[mid]<key)
return(Binary_search(a,mid+1,high,key));
else if(a[mid]==key)
return(mid);
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
}
return(-1);
}
/*output 1:
[mm0528@agni DS]$ cc Binary_SearchNR.c
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 2
Enter a[1] element : 4
Enter a[2] element : 1
Enter a[3] element : 6
Enter a[4] element : 3
Enter searching element : 7
7 is not found
output 2 :
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 4
Enter a[1] element : 6
Enter a[2] element : 1
Enter a[3] element : 3
Enter a[4] element : 2
Enter searching element : 3
3 is found
[mm0528@agni DS]$
*/
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
12)Implement a Binary Search with non recursive
#include<stdio.h>
int Binary_search(int a[],int n,int key);
int main()
{
int a[10];
int i,j,temp,n,key;
printf("Enter the no.of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] element : ",i);
scanf("%d",&a[i]);
}
printf("Enter searching element : ");
scanf("%d",&key);
/* sorting process */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(Binary_search(a,n,key)!=-1)
printf("%d is found",key);
else
printf("%d is not found",key);
}
int Binary_search(int a[],int n,int key)
{
int l,h,mid;
l = 0;
h = n-1;
while(l <= h)
{
mid = (l+h)/2;
if( a[mid] == key)
return mid;
else
if(a[mid] < key)
l = mid+1;
Data Structure Lab
Marri Lakshman Reddy Institute of Technology and management
else
h = mid-1;
}
return -1;
}
/*output 1:
[mm0528@agni DS]$ cc Binary_SearchNR.c
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 2
Enter a[1] element : 4
Enter a[2] element : 1
Enter a[3] element : 6
Enter a[4] element : 3
Enter searching element : 7
7 is not found
output 2 :
[mm0528@agni DS]$ ./a.out
Enter the no.of elements : 5
Enter a[0] element : 4
Enter a[1] element : 6
Enter a[2] element : 1
Enter a[3] element : 3
Enter a[4] element : 2
Enter searching element : 3
3 is found
[mm0528@agni DS]$
*/
Related documents