You are on page 1of 57

EX.4.

A- IMPLEMENTATION OF SINGLY LINKED LIST

#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node()
{
data = 0;
next = NULL;
}
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
class Linkedlist {
Node* head;

public:
Linkedlist() { head = NULL; }
void insertNode(int);
void printList();
void deleteNode(int);
};

void Linkedlist::deleteNode(int nodeOffset)


{
Node *temp1 = head, *temp2 = NULL;
int ListLen = 0;

if (head == NULL) {
cout << "List empty." << endl;
return;
}

while (temp1 != NULL) {


temp1 = temp1->next;
ListLen++;
}

if (ListLen < nodeOffset) {


cout << "Index out of range"
<< endl;
return;
}
temp1 = head;
if (nodeOffset == 1)
{
head = head->next;
delete temp1;
return;
}
while (nodeOffset-- > 1) {
temp2 = temp1;
temp1 = temp1->next;
}

temp2->next = temp1->next;
delete temp1;
}
void Linkedlist::insertNode(int data)
{
Node* newNode = new Node(data);
if (head == NULL) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

void Linkedlist::printList()
{
Node* temp = head;
if (head == NULL) {
cout << "List empty" << endl;
return;
}

while (temp != NULL) {


cout << temp->data << " ";
temp = temp->next;
}
}

int main()
{
Linkedlist list;
list.insertNode(1);
list.insertNode(2);
list.insertNode(3);
list.insertNode(4);

cout << "Elements of the list are: ";

list.printList();
cout << endl;

list.deleteNode(2);

cout << "Elements of the list are: ";


list.printList();
cout << endl;
return 0;
}

Output
Elements of the list are: 1 2 3 4
Elements of the list are: 1 3 4
EX.4.B- CREATE CIRCULAR SINGLY LINKED LIST

#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
struct Node *addToEmpty(struct Node *last, int data)
{
if (last != NULL)
return last;
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp -> data = data;
last = temp;
last -> next = last;
return last;
}
struct Node *addBegin(struct Node *last, int data)
{
if (last == NULL)
return addToEmpty(last, data);
struct Node *temp =
(struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = last -> next;
last -> next = temp;
return last;
}
struct Node *addEnd(struct Node *last, int data)
{
if (last == NULL)
return addToEmpty(last, data);
struct Node *temp =(struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = last -> next;
last -> next = temp;
last = temp;
return last;
}
struct Node *addAfter(struct Node *last, int data, int item)
{
if (last == NULL)
return NULL;
struct Node *temp, *p;
p = last -> next;
do
{
if (p ->data == item)
{
temp = (struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = p -> next;
p -> next = temp;
if (p == last)
last = temp;
return last;
}
p = p -> next;
} while(p != last -> next);
cout << item << " not present in the list." << endl;
return last;
}
void traverse(struct Node *last)
{
struct Node *p;
if (last == NULL)
{
cout << "List is empty." << endl;
return;
}
p = last -> next;
do
{
cout << p -> data << " ";
p = p -> next;
}
while(p != last->next);
}
int main()
{
struct Node *last = NULL;
last = addToEmpty(last, 6);
last = addBegin(last, 4);
last = addBegin(last, 2);
last = addEnd(last, 8);
last = addEnd(last, 12);
last = addAfter(last, 10, 8);
traverse(last);
return 0;
}
Output:
2 4 6 8 10 12
EX.4.C- CREATE DOUBLE LINKED LIST

#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node* prev;
};

void push(Node** head_ref, int new_data)


{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
new_node->prev = NULL;
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
void insertAfter(Node* prev_node, int new_data)
{
if (prev_node == NULL)
{
cout<<"the given previous node cannot be NULL";
return;
}
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
new_node->prev = prev_node;
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
void append(Node** head_ref, int new_data)
{
Node* new_node = new Node();
Node* last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL)
{
new_node->prev = NULL;
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
new_node->prev = last;
return;
}
void printList(Node* node)
{
Node* last;
cout<<"\nTraversal in forward direction \n";
while (node != NULL)
{
cout<<" "<<node->data<<" ";
last = node;
node = node->next;
}

cout<<"\nTraversal in reverse direction \n";


while (last != NULL)
{
cout<<" "<<last->data<<" ";
last = last->prev;
}
}
int main()
{
Node* head = NULL;
append(&head, 6);
push(&head, 7);
push(&head, 1);
append(&head, 4);
insertAfter(head->next, 8);
cout << "Created DLL is: ";
printList(head);
return 0;
}

Output
Created DLL is:
Traversal in forward direction
1 7 8 6 4
Traversal in reverse direction
4 6 8 7 1
EX.5.A- IMPLEMENTATION OF STACK USING ARRAY

#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";
}
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;
}

Output

1) Push in stack
2) Pop from stack
3) Display stack
4) Exit

Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit
EX.5.B- IMPLEMENTATION OF QUEUE USING ARRAY

#include <iostream>
using namespace std;
int queue[100], n = 100, front = - 1, rear = - 1;
void Insert() {
int val;
if (rear == n - 1)
cout<<"Queue Overflow"<<endl;
else {
if (front == - 1)
front = 0;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
rear++;
queue[rear] = val;
}
}
void Delete() {
if (front == - 1 || front > rear) {
cout<<"Queue Underflow ";
return ;
} else {
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
front++;;
}
}
void Display() {
if (front == - 1)
cout<<"Queue is empty"<<endl;
else {
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" ";
cout<<endl;
}
}
int main() {
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
return 0;
}
OUTPUT

1) Insert element to queue


2) Delete element from queue
3) Display all the elements of queue
4) Exit
Enter your choice : 1
Insert the element in queue : 4
Enter your choice : 1
Insert the element in queue : 3
Enter your choice : 1
Insert the element in queue : 5
Enter your choice : 2
Element deleted from queue is : 4
Enter your choice : 3
Queue elements are : 3 5
Enter your choice : 7
Invalid choice
Enter your choice : 4
Exit
EX.6.A- APPLICATIONS OF LIST

// C++ program for Sparse Matrix Representation using Array


#include <iostream>
using namespace std;
int main()
{
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;
int compactMatrix[3][size];
int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}
for (int i=0; i<3; i++)
{
for (int j=0; j<size; j++)
cout <<" "<< compactMatrix[i][j];
cout <<"\n";
}
return 0;
}

Output
001133
242312
345726
EX.6.B- APPLICATION OF STACK

create a C++ program that converts infix expression to the postfix expression

1. #include<iostream>
2. #include<stack>
3. using namespace std;
4. bool IsOperator(char);
5. bool IsOperand(char);
6. bool eqlOrhigher(char, char);
7. string convert(string);
8. int main()
9. {
10. string infix_expression, postfix_expression;
11. int ch;
12. do
13. {
14. cout << " Enter an infix expression: ";
15. cin >> infix_expression;
16. postfix_expression = convert(infix_expression);
17. cout << "\n Your Infix expression is: " << infix_expression;
18. cout << "\n Postfix expression is: " << postfix_expression;
19. cout << "\n \t Do you want to enter infix expression (1/ 0)?";
20. cin >> ch;
21. }
22. while(ch == 1);
23. return 0;
24. }
25. bool IsOperator(char c)
26. {
27. if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^' )
28. return true;
29. return false;
30. }
31. bool IsOperand(char c)
32. {
33. if( c >= 'A' && c <= 'Z')
34. return true;
35. if (c >= 'a' && c <= 'z')
36. return true;
37. if(c >= '0' && c <= '9')
38. return true;
39. return false;
40. }
41. int precedence(char op)
42. {
43. if(op == '+' || op == '-')
44. return 1;
45. if (op == '*' || op == '/')
46. return 2;
47. if(op == '^')
48. return 3;
49. return 0;
50. }
51. bool eqlOrhigher (char op1, char op2)
52. {
53. int p1 = precedence(op1);
54. int p2 = precedence(op2);
55. if (p1 == p2)
56. {
57. if (op1 == '^' )
58. return false;
59. return true;
60. }
61. return (p1>p2 ? true : false);
62. }
63.
64. string convert(string infix)
65. {
66. stack <char> S;
67. string postfix ="";
68. char ch;
69. S.push( '(' );
70. infix += ')';

71. for(int i = 0; i<infix.length(); i++)


72. {
73. ch = infix[i];
74.
75. if(ch == ' ')
76. continue;
77. else if(ch == '(')
78. S.push(ch);
79. else if(IsOperand(ch))
80. postfix += ch;
81. else if(IsOperator(ch))
82. {
83. while(!S.empty() && eqlOrhigher(S.top(), ch))
84. {
85. postfix += S.top();
86. S.pop();
87. }
88. S.push(ch);
89. }
90. else if(ch == ')')
91. {
92. while(!S.empty() && S.top() != '(')
93. {
94. postfix += S.top();
95. S.pop();
96. }
97. S.pop();
98. }
99. }
100. return postfix;
101. }
Output:
EX.6.C- APPLICATION OF QUEUE

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
struct n {
int p;
int info;
struct n *l;
};
class Priority_Queue {
private:
n *f;
public:
Priority_Queue(){
f = NULL;
}
void insert(int i, int p) {
n *t, *q;
t = new n;
t->info = i;
t->p = p;
if (f == NULL || p < f->p) {
t->l= f;
f = t;
} else {
q = f;
while (q->l != NULL && q->l->p <= p)
q = q->l;
t->l = q->l;
q->l = t;
}
}
void del() {
n *t;
if(f == NULL)
cout<<"Queue Underflow\n";
else {
t = f;
cout<<"Deleted item is: "<<t->info<<endl;
f = f->l;
free(t);
}
}
void show(){
n *ptr;
ptr = f;
if (f == NULL)
cout<<"Queue is empty\n";
else {
cout<<"Queue is :\n";
cout<<"Priority Item\n";
while(ptr != NULL) {
cout<<ptr->p<<" "<<ptr->info<<endl;
ptr = ptr->l;
}
}
}
};
int main() {
int c, i, p;
Priority_Queue pq;
Do {
cout<<"1.Insert\n";
cout<<"2.Delete\n";
cout<<"3.Display\n";
cout<<"4.Exit\n";
cout<<"Enter your choice : ";
cin>>c;
switch(c) {
case 1:
cout<<"Input the item value to be added in the queue : ";
cin>>i;
cout<<"Enter its priority : ";
cin>>p;
pq.insert(i, p);
break;
case 2:
pq.del();
break;
case 3:
pq.show();
break;
case 4:
break;
default:
cout<<"Wrong choice\n";
}
}
while(c != 4);
return 0;
}

Output

1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 7
Enter its priority : 2
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 6
Enter its priority : 1
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 3
Enter its priority : 3
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 4
Enter its priority : 3
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 3
Queue is :
Priority Item
16
27
33
34
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 4
EX.7.A- INSERTION SORT
#include<iostream>
using namespace std;
int main()
{
int arr[50], tot, i, j, k, elem, index;
cout<<"Enter the Size for Array: ";
cin>>tot;
cout<<"Enter "<<tot<<" Array Elements: ";
for(i=0; i<tot; i++)
cin>>arr[i];
for(i=1; i<tot; i++)
{
elem = arr[i];
if(elem<arr[i-1])
{
for(j=0; j<=i; j++)
{
if(elem<arr[j])
{
index = j;
for(k=i; k>j; k--)
arr[k] = arr[k-1];
break;
}
}
}
else
continue;
arr[index] = elem;
}
cout<<"\nThe New Array (Sorted Array):\n";
for(i=0; i<tot; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
OUTPUT:
EX.7.B - MERGE SORT

#include<iostream>
using namespace std;
void swapping(int &a, int &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;
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
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;
while(i < nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++;
}else{
array[k] = rarr[j];
j++;
}
k++;
}
while(i<nl) {
array[k] = larr[i];
i++; k++;
}
while(j<nr) {
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;
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];
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);
cout << "Array after Sorting: ";
display(arr, n);
}

Output

Enter the number of elements: 6


Enter elements:
14 20 78 98 20 45
Array before Sorting: 14 20 78 98 20 45
Array after Sorting: 14 20 20 45 78 98

EX.7.C - LINEAR SEARCH

#include<iostream>
using namespace std;
int main()
{
int arr[10], i, num, index;
cout<<"Enter 10 Numbers: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter a Number to Search: ";
cin>>num;
for(i=0; i<10; i++)
{
if(arr[i]==num)
{
index = i;
break;
}
}
cout<<"\nFound at Index No."<<index;
cout<<endl;
return 0;
}

OUTPUT
EX.7.D - BINARY SEARCH

#include<iostream>
using namespace std;
int main()
{
int i, arr[10], num, first, last, middle;
cout<<"Enter 10 Elements (in ascending order): ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter Element to be Search: ";
cin>>num;
first = 0;
last = 9;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<num)
first = middle+1;
else if(arr[middle]==num)
{
cout<<"\nThe number, "<<num<<" found at Position "<<middle+1;
break;
}
else
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
cout<<"\nThe number, "<<num<<" is not found in given Array";
cout<<endl;
return 0;
}

OUTPUT:
EX.8 - HASH TABLES

/*
*C++ Program to Implement Hash Tables
*/
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;
const int TABLE_SIZE = 128;

class HashEntry
{
public:
int key;
int value;
HashEntry(int key, int value)
{
this->key = key;
this->value = value;
}
};

class HashMap
{
private:
HashEntry **table;
public:
HashMap()
{
table = new HashEntry * [TABLE_SIZE];
for (int i = 0; i< TABLE_SIZE; i++)
{
table[i] = NULL;
}
}
int HashFunc(int key)
{
return key % TABLE_SIZE;
}
void Insert(int key, int value)
{
int hash = HashFunc(key);
while (table[hash] != NULL && table[hash]->key != key)
{
hash = HashFunc(hash + 1);
}
if (table[hash] != NULL)
delete table[hash];
table[hash] = new HashEntry(key, value);
}
int Search(int key)
{
int hash = HashFunc(key);
while (table[hash] != NULL && table[hash]->key != key)
{
hash = HashFunc(hash + 1);
}
if (table[hash] == NULL)
return -1;
else
return table[hash]->value;
}

void Remove(int key)


{
int hash = HashFunc(key);
while (table[hash] != NULL)
{
if (table[hash]->key == key)
break;
hash = HashFunc(hash + 1);
}
if (table[hash] == NULL)
{
cout<<"No Element found at key "<<key<<endl;
return;
}
else
{
delete table[hash];
}
cout<<"Element Deleted"<<endl;
}
~HashMap()
{
for (int i = 0; i < TABLE_SIZE; i++)
{
if (table[i] != NULL)
delete table[i];
delete[] table;
}
}
};
int main()
{
HashMap hash;
int key, value;
int choice;
while (1)
{
cout<<"\n----------------------"<<endl;
cout<<"Operations on Hash Table"<<endl;
cout<<"\n----------------------"<<endl;
cout<<"1.Insert element into the table"<<endl;
cout<<"2.Search element from the key"<<endl;
cout<<"3.Delete element at a key"<<endl;
cout<<"4.Exit"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter element to be inserted: ";
cin>>value;
cout<<"Enter key at which element to be inserted: ";
cin>>key;
hash.Insert(key, value);
break;
case 2:
cout<<"Enter key of the element to be searched: ";
cin>>key;
if (hash.Search(key) == -1)
{
cout<<"No element found at key "<<key<<endl;
continue;
}
else
{
cout<<"Element at key "<<key<<" : ";
cout<<hash.Search(key)<<endl;
}
break;
case 3:
cout<<"Enter key of the element to be deleted: ";
cin>>key;
hash.Remove(key);
break;
case 4:
exit(1);
default:
cout<<"\nEnter correct option\n";
}
}
return 0;
}

OUTPUT:
$ g++ hash_table.cpp
$ a.out
----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 12
Enter key at which element to be inserted: 1

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 24
Enter key at which element to be inserted: 2

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 36
Enter key at which element to be inserted: 3

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 48
Enter key at which element to be inserted: 4

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 60
Enter key at which element to be inserted: 5

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 3
Element at key 3 : 36

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 5
Element at key 5 : 60

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 3
Enter key of the element to be deleted: 4
Element Deleted

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 4
No element found at key 4

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 2
Element at key 2 : 24

----------------------
Operations on Hash Table

----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 4
------------------
(program exited with code: 1)
Press return to continue
EX.9 - C++ PROGRAM FOR DIFFERENT TREE TRAVERSALS

#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)
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);

return 0;
}

Output:

Preorder traversal of binary tree is


12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231
EX.10 – BINARY SEARCH TREE (INSERTION RECURSIVELY)

#include <iostream>
using namespace std;

class BST {
int data;
BST *left, *right;
public:
BST();
BST(int);
BST* Insert(BST*, int);
void Inorder(BST*);
};
BST ::BST()
: data(0)
, left(NULL)
, right(NULL)
{
}
BST ::BST(int value)
{
data = value;
left = right = NULL;
}
BST* BST ::Insert(BST* root, int value)
{
if (!root) {
return new BST(value);
}
if (value > root->data) {
root->right = Insert(root->right, value);
}
else if (value < root->data){
root->left = Insert(root->left, value);
}
return root;
}
void BST ::Inorder(BST* root)
{
if (!root) {
return;
}
Inorder(root->left);
cout << root->data << endl;
Inorder(root->right);
}
int main()
{
BST b, *root = NULL;
root = b.Insert(root, 50);
b.Insert(root, 30);
b.Insert(root, 20);
b.Insert(root, 40);
b.Insert(root, 70);
b.Insert(root, 60);
b.Insert(root, 80);

b.Inorder(root);
return 0;
}

OUTPUT:
EX.11- IMPLEMENTATION OF HEAP

#include<iostream>
#include<iomanip>
using namespace std;
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void print(const int *v)
{
int i;
int size = sizeof(v)/sizeof(int)+1;
cout<<"\t";
for ( i = 0; i < size; i++)
cout<<setw(4)<<v[i];
cout<<"\n";
}
void HeapPermute(int v[], int n)
{
int i;
if (n == 1)
print(v);
else
{
for (i = 0; i < n; i++)
{
HeapPermute(v, n-1);
if(n%2 == 1)
swap(&v[0], &v[n-1]);
else
swap(&v[i], &v[n-1]);
}
}
}

int main()
{
int i, n, count = 1;
cout<<"How many numbers do you want to enter: ";
cin>>n;
int num[n];
cout<<"\nEnter the numbers: ";
for (i = 0; i < n; i++)
{
cin>>num[i];
count *= (i+1);
}

// Print the permutation's count.


cout<<"\nThe number of permutations possible is: "<<count<<"\n";
HeapPermute(num, n);
return 0;
}

OUTPUT:
Case 1:
How many numbers you want to enter: 3

Enter the numbers: 1


9
4

The number of permutations possible is: 6


1 9 4
9 1 4
4 1 9
1 4 9
9 4 1
4 9 1

Case 2:
How many numbers you want to enter: 4

Enter the numbers: 11


23
95
31

The number of permutations possible is: 24


11 23 95
23 11 95
95 11 23
11 95 23
23 95 11
95 23 11
31 23 95
23 31 95
95 31 23
31 95 23
23 95 31
95 23 31
31 11 95
11 31 95
95 31 11
31 95 11
11 95 31
95 11 31
31 11 23
11 31 23
23 31 11
31 23 11
11 23 31
23 11 31
EX.12.A – BREADTH FIRST SEARCH TRAVERSAL

#include<bits/stdc++.h>
using namespace std;
class Graph
{
int V;
vector<list<int>> adj;
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};

Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w);
}

void Graph::BFS(int s)
{
vector<bool> visited;
visited.resize(V,false);
list<int> queue;
visited[s] = true;
queue.push_back(s);

while(!queue.empty())
{
s = queue.front();
cout << s << " ";
queue.pop_front();
for (auto adjecent: adj[s])
{
if (!visited[adjecent])
{
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}
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);

cout << "Following is Breadth First Traversal "


<< "(starting from vertex 2) \n";
g.BFS(2);

return 0;
}

Output

Following is Breadth First Traversal (starting from vertex 2)


2031
12.B. DEPTH FIRST SEARCH (DFS TRAVERSAL)
#include <bits/stdc++.h>
using namespace std;
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;
void addEdge(int v, int w);
void DFS(int v);
};

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w);
}

void Graph::DFS(int v)
{
visited[v] = true;
cout << v << " ";
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}

int main()
{
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Depth First Traversal"
" (starting from vertex 2) \n";
g.DFS(2);
return 0;
}

OUTPUT

Following is Depth First Traversal (starting from vertex 2)


2013
EX.13-SINGLE SOURCE SHORTEST PATH

/*
* C++ Program to find SSSP(Single Source Shortest Path)
* in DAG(Directed Acyclic Graphs)
*/
#include <iostream>
#include <conio.h>
using namespace std;
#define INFINITY 999
struct node
{
int from;
}p[7];
int c = 0;
void djikstras(int *a,int b[][7],int *dv)
{
int i = 0,j,min,temp;
a[i] = 1;
dv[i] = 0;
p[i].from = 0;
for (i = 0; i < 7;i++)
{
if (b[0][i] == 0)
{
continue;
}
else
{
dv[i] = b[0][i];
p[i].from = 0;
}
}
while (c < 6)
{
min = INFINITY;
for (i = 0; i < 7; i++)
{
if (min <= dv[i] || dv[i] == 0 || a[i] == 1)
{
continue;
}
else if (min > dv[i])
{
min = dv[i];
}
}
for (int k = 0; k < 7; k++)
{
if (min == dv[k])
{
temp = k;
break;
}
else
{
continue;
}
}
a[temp] = 1;
for (j = 0; j < 7; j++)
{
if (a[j] == 1 || b[temp][j] == 0)
{
continue;
}
else if (a[j] != 1)
{
if (dv[j] > (dv[temp] + b[temp][j]))
{
dv[j] = dv[temp] + b[temp][j];
p[i].from = temp;
}
}
}
c++;
}
for (int i = 0; i < 7; i++)
{
cout<<"from node "<<p[i].from<<" cost is:"<<dv[i]<<endl;
}
}
int main()
{
int a[7];
int dv[7];
for(int k = 0; k < 7; k++)
{
dv[k] = INFINITY;
}
for (int i = 0; i < 7; i++)
{
a[i] = 0;
}
int b[7][7];
for (int i = 0;i < 7;i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
for(int j = 0;j < 7;j++)
{
cin>>b[i][j];
}
}
djikstras(a,b,dv);
getch();
}

Output
enter values for 1 row
0
3
6
0
0
0
0
enter values for 2 row
3
0
2
4
0
0
0
enter values for 3 row
6
2
0
1
4
2
0
enter values for 4 row
0
4
1
0
2
0
4
enter values for 5 row
0
0
4
2
0
2
1
enter values for 6 row
0
0
2
0
2
0
1
enter values for 7 row
0
0
0
4
1
1
0
from node 0 to node 0 minimum cost is:0
from node 0 to node 1 minimum cost is:3
from node 0 to node 2 minimum cost is:5
from node 0 to node 3 minimum cost is:6
from node 0 to node 4 minimum cost is:8
from node 0 to node 5 minimum cost is:7
from node 0 to node 6 minimum cost is:8
EX.14.A - MST

/*
* C++ Program to find MST(Minimum Spanning Tree) using
* Prim's Algorithm
*/
#include <iostream>
#include <conio.h>
using namespace std;
struct node
{
int fr, to, cost;
}p[6];
int c = 0, temp1 = 0, temp = 0;
void prims(int *a, int b[][7], int i, int j)
{
a[i] = 1;
while (c < 6)
{
int min = 999;
for (int i = 0; i < 7; i++)
{
if (a[i] == 1)
{
for (int j = 0; j < 7; )
{
if (b[i][j] >= min || b[i][j] == 0)
{
j++;
}
else if (b[i][j] < min)
{
min = b[i][j];
temp = i;
temp1 = j;
}
}
}
}
a[temp1] = 1;
p[c].fr = temp;
p[c].to = temp1;
p[c].cost = min;
c++;
b[temp][temp1] = b[temp1][temp]=1000;
}
for (int k = 0; k < 6; k++)
{
cout<<"source node:"<<p[k].fr<<endl;
cout<<"destination node:"<<p[k].to<<endl;
cout<<"weight of node"<<p[k].cost<<endl;
}
}
int main()
{
int a[7];
for (int i = 0; i < 7; i++)
{
a[i] = 0;
}
int b[7][7];
for (int i = 0; i < 7; i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
for (int j = 0; j < 7; j++)
{
cin>>b[i][j];
}
}
prims(a, b, 0, 0);
getch();
}

Output
enter values of adjacency matrix for a 7 node graph:
enter values for 1 row
0
3
6
0
0
0
0
enter values for 2 row
3
0
2
4
0
0
0
enter values for 3 row
6
2
0
1
4
2
0
enter values for 4 row
0
4
1
0
2
0
4
enter values for 5 row
0
0
4
2
0
2
1
enter values for 6 row
00
0
2
0
2
0
1
enter values for 7 row
0
0
0
4
1
1
0
MINIMUM SPANNING TREE AND ORDER OF TRAVERSAL:

source node:0
destination node:1
weight of node3
source node:1
destination node:2
weight of node2
source node:2
destination node:3
weight of node1
source node:2
destination node:5
weight of node2
source node:5
destination node:6
weight of node1
source node:6
destination node:4
weight of node1
EX.14.B - Kruskal's algorithm
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
#define edge pair<int, int>
class Graph {
private:
vector<pair<int, edge> > G;
vector<pair<int, edge> > T;
int *parent;
int V;
public:
Graph(int V);
void AddWeightedEdge(int u, int v, int w);
int find_set(int i);
void union_set(int u, int v);
void kruskal();
void print();
};
Graph::Graph(int V) {
parent = new int[V];
for (int i = 0; i < V; i++)
parent[i] = i;
G.clear();
T.clear();
}
void Graph::AddWeightedEdge(int u, int v, int w) {
G.push_back(make_pair(w, edge(u, v)));
}
int Graph::find_set(int i)
{
if (i == parent[i])
return i;
else
return find_set(parent[i]);
}
void Graph::union_set(int u, int v) {
parent[u] = parent[v];
}
void Graph::kruskal() {
int i, uRep, vRep;
sort(G.begin(), G.end());
for (i = 0; i < G.size(); i++) {
uRep = find_set(G[i].second.first);
vRep = find_set(G[i].second.second);
if (uRep != vRep) {
T.push_back(G[i]);
union_set(uRep, vRep);
}
}
}
void Graph::print() {
cout << "Edge :"
<< " Weight" << endl;
for (int i = 0; i < T.size(); i++) {
cout << T[i].second.first << " - " << T[i].second.second << " : "
<< T[i].first;
cout << endl;
}
}
int main() {
Graph g(6);
g.AddWeightedEdge(0, 1, 4);
g.AddWeightedEdge(0, 2, 4);
g.AddWeightedEdge(1, 2, 2);
g.AddWeightedEdge(1, 0, 4);
g.AddWeightedEdge(2, 0, 4);
g.AddWeightedEdge(2, 1, 2);
g.AddWeightedEdge(2, 3, 3);
g.AddWeightedEdge(2, 5, 2);
g.AddWeightedEdge(2, 4, 4);
g.AddWeightedEdge(3, 2, 3);
g.AddWeightedEdge(3, 4, 3);
g.AddWeightedEdge(4, 2, 4);
g.AddWeightedEdge(4, 3, 3);
g.AddWeightedEdge(5, 2, 2);
g.AddWeightedEdge(5, 4, 3);
g.kruskal();
g.print();
return 0;
}
Output:

You might also like