Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
120 views

Dsa Lab File

The document contains the lab file of a student for their Data Structures course. It includes 12 experiments covering various data structures and algorithms implemented in C++ like arrays, stacks, linked lists, trees, and sorting/searching algorithms. Each experiment has multiple questions and programs to perform operations on the relevant data structures like insertion, deletion, traversal and searching.

Uploaded by

Bhupesh Dhapola
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Dsa Lab File

The document contains the lab file of a student for their Data Structures course. It includes 12 experiments covering various data structures and algorithms implemented in C++ like arrays, stacks, linked lists, trees, and sorting/searching algorithms. Each experiment has multiple questions and programs to perform operations on the relevant data structures like insertion, deletion, traversal and searching.

Uploaded by

Bhupesh Dhapola
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 97

AMITY UNIVERSITY MAHARASHTRA

AMITY INSTITUTE OF INFORMATION TECHNOLOGY

Data Structure using C++


LAB FILE
MCA

Submitted to:
TUBA FIRDAUS

Name of the Student: Bhupesh Chandan Dhapola


Program/Semester : MCA IIst Semester
Enrollment Number:  A710145021012
Index
Ass. Topic Date Sign
no.
1. 1. Write a program to create an array and 15/2/ 2022
perform following operations:
 Insertion
 deletion
 searching
 traversing

2. Write a program to create a two dimensional


array and perform searching operation on it.

2. 1. Write a program to find second maximum 23/2/ 2022


element of an array.
2. Write a program to search an element in
array using binary search.

3. Write a program to delete all duplicate


elements from array.  (e.g:  input=>
1,2,1,3,2,4,3,2  output=> 1,2,3,4)
3. 1. Write a program to implement stack using 13/3/ 2022
array.

2. Write a program to convert infix expression


to postfix expression.
4. 1. WAP in C++ to create a inked list. 02/4/2022
2. WAP to count total number of nodes in a
Linked list.
3. WAP to find average of all nodes in a linked
list.
5. 1. WAP to create a linked list and perform 15/4/2022
following operations 
 Insertion at different positions
 Deletion at different positions
 Display all the node of a Linked List
2. WAP to store marks of students in a Linked
list and display average marks.
3. WAP to concatenate two linked list.
4. WAP to implement Stack using Linked List.
5. WAP to implement Queue using Linked List.
number, total marks and percentage and
use  getdata() and display() methods to read
and print N students data (USE ARRAY OF
OBJECTS).
6. 1. Write a program  in C++ to implement doubly 21/4/2022
linked list and perform all operations:
insertion, deletion, traversal, reverse
traversal.

2. Write a program  in C++ to search an element


in a doubly linked list.
7. 1. Write a program to create a binary search 27/4/2022
tree.
8. 1. Write a program in C++ to perform inorder , 11/5/2022
preorder and postorder traversal of tree.
2. Write a program in C++ to search an element
in the Binary search tree.
9. 1. WAP in C++ to perform Selection sort. 18/5/2022
2. WAP in C++ to perform Bubble sort
10. 1. WAP to perform Insertion sort on the array 25/5/2022
entered by user.
2. WAP to perform merge sort on the array
entered by user.
11. 1. Write a program to perform DFS algorithm. 01/6/2022
2. Write a program to perform BFS algorithm.
12. 1. WAP to perform Quick sort on the array 07/6/2022
entered by user.
2. WAP to perform Heap sort on the array
entered by user.

Experiment 1

Q.1. Write a program to create an array and perform following operations:


A. Insertion
B. Deletion
C. Searching
D. Traversing

A. Insertion code -

#include<iostream>

using namespace std;

int main()

int arr[6], i, elem;

cout<<"Enter 5 Array Elements: ";

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

cin>>arr[i];

cout<<"\nEnter Element to Insert: ";

cin>>elem;

arr[i] = elem;

cout<<"\nThe New Array is:\n";

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

cout<<arr[i]<<" ";
cout<<endl;

return 0;

Output –

B. Deletion code –

#include<iostream>
using namespace std;
int main()
{
int arr[100], tot, i, elem, j, found=0;
cout<<"Enter the Size: ";
cin>>tot;
cout<<"Enter "<<tot<<" Array Elements: ";
for(i=0; i<tot; i++)
cin>>arr[i];
cout<<"\nEnter Element to Delete: ";
cin>>elem;
for(i=0; i<tot; i++)
{
if(arr[i]==elem)
{
for(j=i; j<(tot-1); j++)
arr[j] = arr[j+1];
found=1;
i--;
tot--;
}
}
if(found==0)
cout<<"\nElement doesn't found in the Array!";
else
{
cout<<"\nElement Deleted Successfully!";
cout<<"\n\nThe New Array is:\n";
for(i=0; i<tot; i++)
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
Output –

C. Searching code –
#include<iostream>
using namespace std;

void Search(int a[], int n) {


int temp = -1;

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


if (a[i] == n) {
cout << "Element found at position: " << i + 1 << endl;
temp = 0;
break;
}
}

if (temp == -1) {
cout << "No Element Found" << endl;
}

int main() {
int arr[5];
cout << "Please enter 5 elements of the Array" << endl;
for (int i = 0; i < 5; i++) {
cin >> arr[i];
}
cout << "Please enter an element to search" << endl;
int num;
cin >> num;

Search(arr, num);

return 0;
}
Output –

D. Traversing code –
#include <iostream>
using namespace std;
int main()
{
int i, size;
int arr[]={1, 9, 3, 6, 5};
size=sizeof(arr)/sizeof(arr[0]);
cout << "The array elements are: ";
for(i=0;i<size;i++)
cout << "\n" << "arr[" << i << "]= " << arr[i];
return 0;
}

Output –

Q.2. Write a program to create a two dimensional array and perform searching
operation on it.
Code –

#include<iostream>
using namespace std;
int main()
{

int row_size,col_size;

cout<<"Enter the row Size Of the Array:";


cin>>row_size;
cout<<"Enter the columns Size Of the Array:";
cin>>col_size;

int array[row_size][col_size];

int i,j;
cout<<"Enter the Array Element:\n";
for(i=0;i<row_size;i++)
{
for(j=0;j<col_size;j++)
{
cin>>array[i][j];
}
}

int Search_ele;
printf("Enter the search element:");
scanf("%d",&Search_ele);
int flag=0, row, col;
for(i=0;i<row_size;i++)
{
for(j=0;j<col_size;j++)
{
if(array[i][j]==Search_ele)
{
flag=1;
row=i;
col=j;
}
}
}

if(flag==1)
printf("Position of Search Element %d is (%d, %d)",Search_ele,row,col);
else
printf("Given Search Element is not found....");
}

Output –
Experiment 2

1. Write a program to find second maximum element of an array.


2. Write a program to search an element in array using binary search.
3. Write a program to delete all duplicate elements from array.  (e.g: 
input=> 1,2,1,3,2,4,3,2  output=> 1,2,3,4) 

1. Code –

#include <bits/stdc++.h>
using namespace std;

void print2largest(int arr[], int arr_size)


{
int i, first, second;
if (arr_size < 2) {
printf(" Invalid Input ");
return;
}
sort(arr, arr + arr_size);

for (i = arr_size - 2; i >= 0; i--) {


if (arr[i] != arr[arr_size - 1]) {
printf("The second largest element is %d\n", arr[i]);
return;
}
}
printf("There is no second largest element\n");
}
int main()
{
int arr[] = { 7, 5, 12, 10, 10, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
print2largest(arr, n);
return 0;
}

Output –

2. Code –

#include <bits/stdc++.h>
using namespace std;

int binarySearch(int arr[], int l, int r, int x)


{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}

int main(void)
{

int arr[] = { 75, 70, 80, 60, 90 };


int x = 80;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in array
: cout << "Element is present at index " << result;
return 0;
}

Output –
3. Code –

include<iostream>
using namespace std;
int main ()
{
int A[10], B[10], n, i, j, k = 0;
cout << "Enter size of array : ";
cin >> n;
cout << "Enter elements of array : ";
for (i = 0; i < n; i++)
cin >> A[i];
for (i = 0; i < n; i++)
{
for (j = 0; j < k; j++)
{
if (A[i] == B[j])
break;
}
if (j == k)
{
B[k] = A[i];
k++;
}
}
cout << "Repeated elements after deletion : ";
for (i = 0; i < k; i++)
cout << B[i] << " ";
return 0;
}

Output –
Experiment 3

1. Write a program to implement stack using array.

Code:

#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";

20
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

21
Output:

22
2. Write a program to convert infix expression to postfix expression.

Code:

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}

int main()
{
23
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}return 0;
}

24
Output:

25
Experiment 4

1. WAP in C++ to create a inked list.


2. WAP to count total number of nodes in a Linked list.
3. WAP to find average of all nodes in a linked list.

Code :-

1.

#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node* head =
NULL;
void insert(int new_data)
{

struct Node* new_node =


(struct Node*)
malloc(sizeof(struct
Node));
new_node->data =
new_data;

new_node->next = head;
head = new_node;
}
void display() {
struct Node* ptr;
ptr = head;
while (ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
26
}
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is:
";
display();
return 0;
}

Output

2.

Code:

#include <iostream>
using namespace std;

//node structure
struct Node {
int data;
Node* next;
};

27
class LinkedList {
private:
Node* head;
public:
LinkedList(){
head = NULL;
}

//Add new element at the end of the list


void push_back(int newElement) {
Node* newNode = new Node();
newNode->data = newElement;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
} else {
Node* temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
}

//count nodes in the list


int countNodes() {
Node* temp = head;
int i = 0;
while(temp != NULL) {
i++;
temp = temp->next;
}
return i;
}

//display the content of the list


void PrintList() {
Node* temp = head;

28
if(temp != NULL) {
cout<<"The list contains: ";
while(temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
} else {
cout<<"The list is empty.\n";
}
}
};

// test the code


int main() {
LinkedList MyList;

//Add four elements in the list.


MyList.push_back(10);
MyList.push_back(20);
MyList.push_back(30);
MyList.push_back(40);

//Display the content of the list.


MyList.PrintList();

//number of nodes in the list


cout<<"No. of nodes: "<<MyList.countNodes();

return 0;
}
Output

29
3.

Code:

// C++ implementation to find the average of


// nodes of the Linked List

#include <bits/stdc++.h>
using namespace std;

/* A Linked list node */


struct Node {
int data;
struct Node* next;
};

// function to insert a node at the


// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;

/* put in the data */


new_node->data = new_data;

/* link the old list to the new node */


new_node->next = (*head_ref);

30
/* move the head to point to the new node */
(*head_ref) = new_node;
}

// Function to iteratively find the avg of


// nodes of the given linked list
float avgOfNodes(struct Node* head)
{
// if head = NULL
if (!head)
return -1;

int count = 0; // Initialize count


int sum = 0;
float avg = 0.0;

struct Node* current = head; // Initialize current


while (current != NULL) {
count++;
sum += current->data;
current = current->next;
}

// calculate average
avg = (double)sum / count;

return avg;
}

// Driver Code
int main()
{
struct Node* head = NULL;

// create linked list 7->6->8->4->1


push(&head, 7);
push(&head, 6);

31
push(&head, 8);
push(&head, 4);
push(&head, 1);

cout << "Average of nodes = " << avgOfNodes(head);

return 0;
}

Output :

32
Experiment 5

1.     WAP to create a linked list and perform following operations 


  Insertion at different positions
 Deletion at different positions
 Display all the node of a Linked List

// Linked list operations in C++

#include <stdlib.h>

#include <iostream>
using namespace std;

// Create a node
struct Node {
int data;
struct Node* next;
};

void insertAtBeginning(struct Node** head_ref, int new_data) {


// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data;
new_node->next = (*head_ref);

// Move head to new node


(*head_ref) = new_node;
}

33
// Insert a node after a node
void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
cout << "the given previous node cannot be NULL";
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}

// Insert at the end


void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/

new_node->data = new_data;
new_node->next = NULL;

if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

while (last->next != NULL) last = last->next;

last->next = new_node;
return;
}

// Delete a node
void deleteNode(struct Node** head_ref, int key) {

34
struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key) {


*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present


if (temp == NULL) return;

// Remove the node


prev->next = temp->next;

free(temp);
}

// Print the linked list


void printList(struct Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}

// Driver program
int main() {
struct Node* head = NULL;

35
insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);

cout << "Linked list: ";


printList(head);

cout << "\nAfter deleting an element: ";


deleteNode(&head, 3);
printList(head);

Output:

36
 WAP to store marks of students in a Linked list and display average
marks.

#include <bits/stdc++.h>
using namespace std;

/* A Linked list node */


struct Node {
int data;
struct Node* next;
};

// function to insert a node at the


// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;

/* put in the data */


new_node->data = new_data;

/* link the old list to the new node */


new_node->next = (*head_ref);

/* move the head to point to the new node */


(*head_ref) = new_node;
}

// Function to iteratively find the avg of


// nodes of the given linked list
float avgOfMarks(struct Node* head)
{
// if head = NULL

37
if (!head)
return -1;

int count = 0; // Initialize count


int sum = 0;
float avg = 0.0;

struct Node* current = head; // Initialize current


while (current != NULL) {
count++;
sum += current->data;
current = current->next;
}

// calculate average
avg = (double)sum / count;

return avg;
}

// Driver Code
int main()
{
struct Node* head = NULL;

// create linked list 7->6->8->4->1


push(&head, 70);
push(&head, 60);
push(&head, 80);
push(&head, 90);
push(&head, 90);

cout << "Average of Marks= " << avgOfMarks(head);

38
return 0;
}

Output:

 WAP to concatenate two linked list.

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

struct node
{
int info;
struct node *link;
};
struct node *create_list(struct node *);
struct node *concat( struct node *start1,struct node *start2);
struct node *addatbeg(struct node *start, int data);
struct node *addatend(struct node *start,int data);
void display(struct node *start);

39
int main()
{
struct node *start1=NULL,*start2=NULL;
start1=create_list(start1);
start2=create_list(start2);
printf("\nFirst list is : ");
display(start1);
printf("\nSecond list is : ");
display(start2);
start1=concat(start1, start2);
printf("\nConcatenated list is : ");
display(start1);

return 0;

}
//End of main()/

struct node *concat( struct node *start1,struct node *start2)


{
struct node *ptr;
if(start1==NULL)
{
start1=start2;
return start1;
}
if(start2==NULL)
return start1;
ptr=start1;
while(ptr->link!=NULL)
ptr=ptr->link;
ptr->link=start2;
return start1;
}

40
struct node *create_list(struct node *start)
{
int i,n,data;
printf("\nEnter the number of nodes : ");
scanf("%d",&n);
start=NULL;
if(n==0)
return start;

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


scanf("%d",&data);
start=addatbeg(start,data);

for(i=2;i<=n;i++)
{
printf("Enter the element to be inserted : ");
scanf("%d",&data);
start=addatend(start,data);
}
return start;
}
//End of create_list()/

void display(struct node *start)


{
struct node *p;
if(start==NULL)
{
printf("\nList is empty\n");
return;
}
p=start;
while(p!=NULL)
{

41
printf("%d ", p->info);
p=p->link;
}
printf("\n");
}/*End of display() */

struct node *addatbeg(struct node *start,int data)


{
struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=start;
start=tmp;
return start;
}
//End of addatbeg()/

struct node *addatend(struct node *start, int data)


{
struct node *p,*tmp;
tmp= (struct node *)malloc(sizeof(struct node));
tmp->info=data;
p=start;
while(p->link!=NULL)
p=p->link;
p->link=tmp;
tmp->link=NULL;
return start;
}
//End of addatend()/

42
Output:

 WAP to implement Stack using Linked List.

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

// Structure to create a node with data and next pointer


struct Node {
int data;
struct Node *next;
};
Node* top = NULL;

// Push() operation on a stack


void push(int value) {
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value; // assign value to the node
if (top == NULL) {
newNode->next = NULL;
} else {
newNode->next = top; // Make the node as top

43
}
top = newNode; // top always points to the newly created node
printf("Node is Inserted\n\n");
}

int pop() {
if (top == NULL) {
printf("\nStack Underflow\n");
} else {
struct Node *temp = top;
int temp_data = top->data;
top = top->next;
free(temp);
return temp_data;
}
}

void display() {
// Display the elements of the stack
if (top == NULL) {
printf("\nStack Underflow\n");
} else {
printf("The stack is \n");
struct Node *temp = top;
while (temp->next != NULL) {
printf("%d--->", temp->data);
temp = temp->next;
}
printf("%d--->NULL\n\n", temp->data);
}
}

int main() {
int choice, value;

44
printf("\nImplementaion of Stack using Linked List\n");
while (1) {
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", &value);
push(value);
break;
case 2:
printf("Popped element is :%d\n", pop());
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
}

Output:

45
46
 WAP to implement Queue using Linked List.

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

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");

47
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:

48
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create an empty queue */


void create()
{
front = rear = NULL;
}

/* Returns queue size */


void queuesize()
{
printf("\n Queue size : %d", count);
}

/* Enqueing the queue */


void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;

49
rear = temp;
}
count++;
}

/* Displaying the queue elements */


void display()
{
front1 = front;

if ((front1 == NULL) && (rear == NULL))


{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}

/* Dequeing the queue */


void deq()
{
front1 = front;

if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;

50
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}

/* Returns the front element of queue */


int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

/* Display if queue is empty or not */


void empty()

51
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

Output:

52
Experiment 6

1. Write a program  in C++ to implement doubly linked list and perform all
operations: insertion, deletion, traversal, reverse traversal.
Code:
#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;


struct node
{
int info;
struct node *next;
struct node *prev;
}*start;

class double_llist
{
public:
void create_list(int value);
void add_begin(int value);
void add_after(int value, int position);
void delete_element(int value);
void search_element(int value);
void display_dlist();
void count();
void reverse();
double_llist()
{
start = NULL;
}
};

int main()
{

53
int choice, element, position;
double_llist dl;
while (1)
{
cout<<endl<<"----------------------------"<<endl;
cout<<endl<<"Operations on Doubly linked list"<<endl;
cout<<endl<<"----------------------------"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at begining"<<endl;
cout<<"3.Add after position"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Count"<<endl;
cout<<"7.Reverse"<<endl;
cout<<"8.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch ( choice )
{
case 1:
cout<<"Enter the element: ";
cin>>element;
dl.create_list(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element: ";
cin>>element;
dl.add_begin(element);
cout<<endl;
break;
case 3:
cout<<"Enter the element: ";
cin>>element;
cout<<"Insert Element after postion: ";
cin>>position;
dl.add_after(element, position);
54
cout<<endl;
break;
case 4:
if (start == NULL)
{
cout<<"List empty,nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
dl.delete_element(element);
cout<<endl;
break;
case 5:
dl.display_dlist();
cout<<endl;
break;
case 6:
dl.count();
break;
case 7:
if (start == NULL)
{
cout<<"List empty,nothing to reverse"<<endl;
break;
}
dl.reverse();
cout<<endl;
break;
case 8:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}
55
void double_llist::create_list(int value)
{
struct node *s, *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}

void double_llist::add_begin(int value)


{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->prev = NULL;
temp->info = value;
temp->next = start;
start->prev = temp;
start = temp;
56
cout<<"Element Inserted"<<endl;
}

void double_llist::add_after(int value, int pos)


{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *tmp, *q;
int i;
q = start;
for (i = 0;i < pos - 1;i++)
{
q = q->next;
if (q == NULL)
{
cout<<"There are less than ";
cout<<pos<<" elements."<<endl;
return;
}
}
tmp = new(struct node);
tmp->info = value;
if (q->next == NULL)
{
q->next = tmp;
tmp->next = NULL;
tmp->prev = q;
}
else
{
tmp->next = q->next;
tmp->next->prev = tmp;
q->next = tmp;
tmp->prev = q;
57
}
cout<<"Element Inserted"<<endl;
}

void double_llist::delete_element(int value)


{
struct node *tmp, *q;
//first element deletion/
if (start->info == value)
{
tmp = start;
start = start->next;
start->prev = NULL;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = start;
while (q->next->next != NULL)
{
//Element deleted in between/
if (q->next->info == value)
{
tmp = q->next;
q->next = tmp->next;
tmp->next->prev = q;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = q->next;
}
//last element deleted/
if (q->next->info == value)
{
tmp = q->next;
free(tmp);
58
q->next = NULL;
cout<<"Element Deleted"<<endl;
return;
}
cout<<"Element "<<value<<" not found"<<endl;
}

void double_llist::display_dlist()
{
struct node *q;
if (start == NULL)
{
cout<<"List empty,nothing to display"<<endl;
return;
}
q = start;
cout<<"The Doubly Link List is :"<<endl;
while (q != NULL)
{
cout<<q->info<<" <-> ";
q = q->next;
}
cout<<"NULL"<<endl;
}

void double_llist::count()
{
struct node *q = start;
int cnt = 0;
while (q != NULL)
{
q = q->next;
cnt++;
}
cout<<"Number of elements are: "<<cnt<<endl;
}
59
void double_llist::reverse()
{
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != NULL)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
start = p1;
cout<<"List Reversed"<<endl;
}

60
Output:

61
62
63
64
65
2. Write a program in C++ to search an element in a doubly linked list.
Code:
#include <stdio.h>
#include <stdlib.h>

//structure of Node with prev and next pointers


struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
void createList(int n);
void displayList();
void search_element(int data);

int main()
{
int n, data;
head = NULL;
last = NULL;
printf("\nEnter the total number of nodes in list : ");
// Input the number of nodes
scanf("%d", &n);
createList(n);
printf("\n\nTHE DOUBLY LINKED LIST IS :\n\n");
displayList();
printf("\n\nEnter the element you want to search : ");
scanf("%d",&data);
search_element(data);
return 0;
}

void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
66
{
head = (struct node *)malloc(sizeof(struct node));
printf("\nEnter data of node 1 : ");
scanf("%d", &data);
head->data = data;
head->prev = NULL; // HEAD nodes's prev is set to NULL
head->next = NULL; // HEAD nodes's next is set to NULL
last = head;
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("\nEnter data of node %d : ", i);
scanf("%d", &data);
newNode->data = data;
newNode->prev = last; // Link new node with the previous node
newNode->next = NULL;
last->next = newNode; // Link previous node with the new node
last = newNode; // Make new node as last node
}}}
void displayList()
{
struct node * temp;
int n = 1;
if(head == NULL)
{
printf("\nList is empty.\n");
}
else
{
temp = head;
while(temp != NULL)
{
printf("%d\t", temp->data);
n++;
/* Move the current pointer to next node */
temp = temp->next;
}}}
67
void search_element(int data)
{
struct node * temp = (struct node *)malloc(sizeof(struct node));
temp = head;
int pos = 0;
while(temp != NULL)
{
if(temp -> data == data) // Element is found
{
printf("\n\nThe element %d is at index %d in the list", data,pos); //If
found, print and exit
exit(0);
}
else
{
temp = temp ->next; //If not found, traverse the list
pos++;
}
}
printf("\n\nThe element %d is not found in the list",data);
}

Output:

68
69
Experiment 7

1. Write a program to create a binary search tree.


Code:

#include <iostream>
using namespace std;

struct tree
{
tree *l, *r;
int data;
}*root = NULL, *p = NULL, *np = NULL, *q;

void create()
{
int value,c = 0;
while (c < 7)
{
if (root == NULL)
{
root = new tree;
cout<<"enter value of root node\n";
cin>>root->data;
root->r=NULL;
root->l=NULL;
}
else
{
p = root;
cout<<"enter value of node\n";
cin>>value;
while(true)
{
if (value < p->data)
{

70
if (p->l == NULL)
{
p->l = new tree;
p = p->l;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in left\n";
break;
}
else if (p->l != NULL)
{
p = p->l;
}
}
else if (value > p->data)
{
if (p->r == NULL)
{
p->r = new tree;
p = p->r;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in right\n";
break;
}
else if (p->r != NULL)
{
p = p->r;
}
}
}
}
c++;
}
}
71
void inorder(tree *p)
{
if (p != NULL)
{
inorder(p->l);
cout<<p->data;
inorder(p->r);
}
}
void preorder(tree *p)
{
if (p != NULL)
{
cout<<p->data;
preorder(p->l);
preorder(p->r);
}
}
void postorder(tree *p)
{
if (p != NULL)
{
postorder(p->l);
postorder(p->r);
cout<<p->data;
}
}
int main()
{
create();
cout<<"\n Printing traversal in Inorder\n";
inorder(root);
cout<<"\n Printing traversal in Preorder\n";
preorder(root);
cout<<"\n Printing traversal in Postorder\n";
postorder(root);

72
}

OUTPUT

73
Experiment 8
1. Write a program in C++ to perform inorder , preorder and postorder
traversal of tree.

#include <iostream>
using namespace std;

struct Node {
int data;
struct Node *left, *right;
};
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}

void printPostorder(struct Node* node)


{
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right);

cout << node->data << " ";


}

void printInorder(struct Node* node)


{
if (node == NULL)

74
return;
printInorder(node->left);
cout << node->data << " ";

printInorder(node->right);
}

void printPreorder(struct Node* node)


{
if (node == NULL)
return;

cout << node->data << " ";

printPreorder(node->left);
printPreorder(node->right);
}

int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

cout << "\nPreorder traversal of binary tree is \n";


printPreorder(root);

cout << "\nInorder traversal of binary tree is \n";


printInorder(root);

cout << "\nPostorder traversal of binary tree is \n";


printPostorder(root);

75
return 0;
}

OUTPUT:

2. Write a program in C++ to search an element in the Binary search tree.

#include<iostream>
using namespace std;
struct node {
   int d;
   node *left;
   node *right;
};
node* CreateNode(int d) {
   node *newnode = new node;
   newnode->d = d;
   newnode->left = NULL;
   newnode->right = NULL;
   return newnode;
}
node* InsertIntoTree(node* root, int d) {
   node *temp = CreateNode(d);
   node *t = new node;
   t = root;
   if(root == NULL)
      root = temp;

76
   else {
      while(t != NULL) {
         if(t->d < d) {
            if(t->right == NULL) {
               t->right = temp;
               break;
      }
            t = t->right;
         } else if(t->d > d) {
            if(t->left == NULL) {
               t->left = temp;
               break;
      }
            t = t->left;
         }
   }
   }
   return root;
}
void Search(node *root, int d) {
   int depth = 0;
   node *temp = new node;
   temp = root;
   while(temp != NULL) {
      depth++;
      if(temp->d == d) {
         cout<<"\nitem found at depth: "<<depth;
         return;
      } else if(temp->d > d)
         temp = temp->left;
         else
            temp = temp->right;
   }
   cout<<"\n item not found";
   return;
}
int main() {
77
   char ch;
   int n, i, a[10] = {93, 53, 45, 2, 7, 67, 32, 26, 71, 76};
   node *root = new node;
   root = NULL;
   for (i = 0; i < 10; i++)
      root = InsertIntoTree(root, a[i]);
   up:
   cout<<"\nEnter the Element to be searched: ";
   cin>>n;
   Search(root, n);
   cout<<"\n\n\tDo you want to search more...enter choice(y/n)?";
   cin>>ch;
   if(ch == 'y' || ch == 'Y')
      goto up;
   return 0;
}

OUTPUT:

78
Experiment 9
WAP in C++ to perform Selection sort.

#include <bits/stdc++.h>
using namespace std;

//Swap function
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of


// unsorted subarray
for (i = 0; i < n-1; i++)
{

// Find the minimum element in


// unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element


// with the first element
swap(&arr[min_idx], &arr[i]);
}

79
}

//Function to print an array


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}

80
WAP in C++ to perform Bubble sort.

#include <bits/stdc++.h>
using namespace std;

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)

// Last i elements are already


// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}

// Function to print an array


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

// Driver code
int main()
{
int arr[] = { 5, 1, 4, 2, 8};
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
cout << "Sorted array: \n";
printArray(arr, N);
return 0;

81
}

82
Experiment 10

1. WAP to perform Insertion sort on the array entered by the user.

Code:

#include<iostream>
using namespace std;
void display(int *array,
int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void insertionSort(int
*array, int size) {
int key, j;
for(int i = 1; i<size; i++)
{
key = array[i];//take
value
j = i;
while(j > 0 &&
array[j-1]>key) {
array[j] = array[j-1];
j--;
}
array[j] = key;
//insert in right place
}
}
int main() {
int n;
cout << "Enter the
number of elements: ";
cin >> n;
83
int arr[n]; //create an
array with given number
of elements
cout << "Enter
elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before
Sorting: ";
display(arr, n);
insertionSort(arr, n);
cout << "Array after
Sorting: ";
display(arr, n);
}

Output :

84
WAP to perform merge sort on the array entered by the user.

Code:

#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void merge(int *array, int l, int m, int r) {
int i, j, k, nl, nr;
//size of left and right sub-arrays
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
//fill left and right sub-arrays
for(i = 0; i<nl; i++)
larr[i] = array[l+i];
for(j = 0; j<nr; j++)
rarr[j] = array[m+1+j];
i = 0; j = 0; k = l;
//marge temp arrays to real array
while(i < nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++;
}else{
array[k] = rarr[j];
j++;
}
85
k++;
}
while(i<nl) { //extra element in left array
array[k] = larr[i];
i++; k++;
}
while(j<nr) { //extra element in right array
array[k] = rarr[j];
j++; k++;
}
}
void mergeSort(int *array, int l, int r) {
int m;
if(l < r) {
int m = l+(r-l)/2;
// Sort first and second arrays
mergeSort(array, l, m);
mergeSort(array, m+1, r);
merge(array, l, m, r);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
mergeSort(arr, 0, n-1); //(n-1) for last index
cout << "Array after Sorting: ";
display(arr, n);
}

86
Output:

87
Experiment 11

1. Write a program to perform DFS algorithm.


Code :-
#include <iostream>
#include<vector>
using namespace std;

int main()
{

int cost[10][10], i, j, k, n, e, top, v, stk[10], visit[10], visited[10];

cout << "Enter the number of vertices in the Graph: ";


cin >> n;
cout << "\nEnter the number of edges in the Graph : ";
cin >> e;
cout << "\nEnter the start and end vertex of the edges: \n";

for (k = 1; k <= e; k++)


{
cin >> i >> j;
cost[i][j] = 1;
}

cout << "\nEnter the initial vertex to start the DFS traversal with: ";
cin >> v;
cout << "\nThe DFS traversal on the given graph is : \n";
cout << v << " ";

visited[v] = 1;

k = 1;

while (k < n)

88
{
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];
cout << v << " ";
k++;

visit[v] = 0;

visited[v] = 1;
}

cout << "\n\n\n";

return 0;
}

89
OUTPUT:

90
2. Write a program to perform BFS algorithm.
Code :-

#include <iostream>
#include <list>

using namespace std;

class Graph {
  int numVertices;
  list<int>* adjLists;
  bool* visited;

   public:
  Graph(int vertices);
  void addEdge(int src, int dest);
  void BFS(int startVertex);
};

Graph::Graph(int vertices) {
  numVertices = vertices;
  adjLists = new list<int>[vertices];
}

void Graph::addEdge(int src, int dest) {


  adjLists[src].push_back(dest);
  adjLists[dest].push_back(src);
}

void Graph::BFS(int startVertex) {


  visited = new bool[numVertices];
  for (int i = 0; i < numVertices; i++)
    visited[i] = false;

  list<int> queue;
91
  visited[startVertex] = true;
  queue.push_back(startVertex);

  list<int>::iterator i;

  while (!queue.empty()) {
    int currVertex = queue.front();
    cout << "Visited " << currVertex << " ";
    queue.pop_front();

    for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i) {


      int adjVertex = *i;
      if (!visited[adjVertex]) {
        visited[adjVertex] = true;
        queue.push_back(adjVertex);
   }
  }
 }
}

int main() {
  Graph g(4);
  g.addEdge(0, 1);
  g.addEdge(0, 2);
  g.addEdge(1, 2);
  g.addEdge(2, 0);
  g.addEdge(2, 3);
  g.addEdge(3, 3);

  g.BFS(2);

  return 0;
}

92
OUTPUT:

93
Experiment 12

Q1) Wap to perform Quick sort on the array entered by user.

#include<iostream>
using namespace std;
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int m=1;
int partition (int arr[], int low, int high)
{int j,k;
int pivot = arr[low];
int i = low ;
for(j = low+1;j<= high; j++)
{
if (arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
} }
swap(&arr[i] , &arr[low]);

return (i);
}
void quickSort(int arr[], int low, int high)
{ int r,i,k;
if (low < high)
{
r = partition(arr, low, high);
quickSort(arr, low, r - 1);

94
quickSort(arr, r + 1, high);

}
}

int main()
{
int arr[] = {6,15,3,9, 18, 4, 10, 27, 25},i;
quickSort(arr, 0, 8);
cout<<"\t\t\nSorted array: ";
for(i=0; i <=8; i++)
cout<<arr[i]<<"\t";
return 0;
}

Output:

95
2. Wap to perform Quick sort on the array entered by user.

#include <iostream>
using namespace std;
void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;

if (l < n && arr[l] > arr[largest])


largest = l;

if (r < n && arr[r] > arr[largest])


largest = r;

if (largest != i)
{
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n)


{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (int i=n-1; i>=0; i--)


{
swap(arr[0], arr[i]);

heapify(arr, i, 0);
}
}

96
int main()
{
int arr[] = {52, 25, 24, 8, 11};
int n = 5;
cout << "Unsorted array \n";
for (int i = 0; i < n; i++)
{
cout << arr[i] << "\t";
}

heapSort(arr, n);

cout << "Sorted array \n";


for (int i = 0; i < n; i++)
{
cout << arr[i] << "\t";
}
}
Output:

***************************************************************************

97

You might also like