You are on page 1of 85

INDEX

S.no Title of programme


1. WAP to find the mean and median of no stored in array

2. WAP to insert an element in one array and delete one


element from an array
3. WAP to search for an number in an array

4. WAP to sort an array

5. WAP to merge two sorted arrays

6. WAP to store mark obtained by 10 students in 5 subjects


in 2 dimensional array
7. WAP to implement the linked list

8. WAP to insert node in linked list and delete a node

9. WAP to print elements in reverse order in linked list


without disturbing the linked list
10. WAP to reverse a linked list

11. WAP to add two polynomials using linked list.

12. WAP to implement doubly linked list.

13. WAP to implement a stack using array.

14. WAP to implement stack using linked list.

15. WAP to implement queue using array.

16. WAP to implement queue using linked list.

17. WAP to implement circular queue using arrays.

18. WAP to implement priority queue using linked list.


19. WAP to implement double ended queue using a linked
list.
20. WAP to construct a binary tree and display its
preorder,inorder and post order traversals.
21. WAP to construct a binary search tree.

22. WAP to construct a graph.

23. WAP to calculate the distance between two vertices in a


graph.
24. WAP to calculate distance between every pair of vertices
in a graph .
25. WAP to construct a minimal spanning tree of a graph.

PROGRAMMES :
WAP to find the mean and median of no stored in array
#include <iostream>
using namespace std;

// Function for calculating mean


double findMean(int a[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];

return (double)sum/(double)n;
}
// Function for calculating median
double findMedian(int a[], int n)
{
// First we sort the array
for (int i=0; i<n ; ++i)
{
cout<<a[i]<<" ";
}

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


{
for (int j=i+1; j<n; ++j)
{
if(a[j]<a[i])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
// check for even case
if (n % 2 != 0)
return (double)a[n/2];

return (double)(a[(n-1)/2] + a[n/2])/2.0;


}

// Driver program
int main()
{
int a[] = {100,200,300,400,500,600,700,800};
int n = sizeof(a)/sizeof(a[0]);
cout << "Mean = " << findMean(a, n) << endl;
cout << "Median = " << findMedian(a, n) << endl;
return 0;
}

2. WAP to insert an element in one array and delete one element


from an array.
#include <iostream>
using namespace std;
// Inserts a key in arr[] of given capacity.
// n is current size of arr[]. This
// function returns n + 1 if insertion
// is successful, else n.
int insertSorted(int arr[], int n, int key, int capacity)
{

// Cannot insert more elements if n is


// already more than or equal to capcity
if (n >= capacity)
return n;

arr[n] = key;

return (n + 1);
}

// Driver Code
int main()
{
int arr[20] = {100,200,300,400,500,600};
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 226;
cout << "\n Before Insertion: ";
for (i = 0; i < n; i++)
cout << arr[i]<< " ";

// Inserting key
n = insertSorted(arr, n, key, capacity);

cout << "\n After Insertion: ";


for (i = 0; i < n; i++)
cout << arr[i] << " ";

return 0;
}

3. WAP to search for an number in an array.


// C++ code to linearly search x in arr[]. If x
// is present then return its location, otherwise
// return -1

#include <iostream>
using namespace std;
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}

int main(void)
{
int arr[] = { 100,200,300,400,500 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, n, x);
if(result == -1)
cout<<"Element is not present in array";
else
cout<<"Element is present at index " <<result;
return 0;
}
4. WAP to sort an array.
#include<iostream>
using namespace std;
int main()
{

int arr[]={400,500,200,100,300};
int n=5;
cout<<"unsorted array : ";
for (int i = 0; i < n; ++i)
{
cout<<arr[i]<<" ";
}
for (int i=0;i<n;++i)
{
for (int j=i+1; j<n; ++j)
{
if(arr[j]<arr[i])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

cout<<"\nsorted array : ";


for (int i = 0; i <n; ++i)
{
cout<<arr[i]<<" ";
}
return 0;
}

5. WAP to merge two sorted arrays.


#include<iostream>
using namespace std;

// Merge arr1[0..n1-1] and arr2[0..n2-1] into


// arr3[0..n1+n2-1]
void mergeArrays(int arr1[], int arr2[], int n1,
int n2, int arr3[])
{
int i = 0, j = 0, k = 0;

// Traverse both array


while (i<n1 && j <n2)
{
// Check if current element of first
// array is smaller than current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (arr1[i] < arr2[j])
arr3[k++] = arr1[i++];
else
arr3[k++] = arr2[j++];
}

// Store remaining elements of first array


while (i < n1)
arr3[k++] = arr1[i++];

// Store remaining elements of second array


while (j < n2)
arr3[k++] = arr2[j++];
}

// Driver code
int main()
{
int arr1[] = {1, 3, 5, 7};
int n1 = sizeof(arr1) / sizeof(arr1[0]);

int arr2[] = {2, 4, 6, 8};


int n2 = sizeof(arr2) / sizeof(arr2[0]);

int arr3[n1+n2];
mergeArrays(arr1, arr2, n1, n2, arr3);

cout << "Array after merging" <<endl;


for (int i=0; i < n1+n2; i++)
cout << arr3[i] << " ";

return 0;
}
6. WAP to store mark obtained by 10 students in 5 subjects in 2
dimensional array
#include<iostream>
using namespace std;
int main()
{
int arr[10][5];
for(int i=0;i<10;i++)
{
cout<<"Enter Marks of student "<<i+1<<": ";
for(int j=0;j<5;j++)
{
cin>>arr[i][j];
}
cout<<endl;
}

return 0;
}
7. WAP to implement the linked list
#include <iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

class LL
{
Node* head = NULL;
public:
KK(int new_data)
{
Node* n = new Node;
n->data = new_data;
n->next = nullptr;
head = n;
}
void insertNode(int new_data)
{
Node* temp = head;
while(temp->next != nullptr)
{
temp = temp->next;
}
Node* n = new Node;
n->data = new_data;
n->next = nullptr;
temp->next = n;
}
void deleteNode(int position)
{
if(position == 0)
{
Node* temp = head;
head = head->next;
delete temp;
}
Node* temp = head;
Node* prev = head;
while(position > 0 && temp->next != nullptr)
{
prev = temp;
temp = temp->next;
position--;
}
if(position != 0)
{
cout << "Error";
return;
}
prev->next = temp->next;
delete temp;
}
int search(int query)
{
Node* temp = head;
int position = 0;
while(temp != nullptr)
{
if(temp->data == query)
{
return position;
}
position++;
temp = temp->next;
}
return position;
}
void print()
{
Node* temp = head;
while(temp != nullptr)
{
cout << temp->data << " ";
temp = temp->next;
}
}
};

int main()
{
KK* myLinkedList = new KK(1);
myLinkedList->insertNode(100);
myLinkedList->insertNode(200);
myLinkedList->insertNode(300);
myLinkedList->insertNode(400);
myLinkedList->insertNode(500);
myLinkedList->print();
cout << endl;

return 0;
}

8. WAP to insert node in linked list and delete a node


#include <iostream>
using namespace std;

class Node
{
public:
int data;
Node* next;
};
class KK
{
Node* head = nullptr;
public:
KK(int new_data)
{
Node* n = new Node;
n->data = new_data;
n->next = nullptr;
head = n;
}
void insertNode(int new_data)
{
Node* temp = head;
while(temp->next != nullptr)
{
temp = temp->next;
}
Node* n = new Node;
n->data = new_data;
n->next = nullptr;
temp->next = n;
}
void deleteNode(int position)
{
if(position == 0)
{
Node* temp = head;
head = head->next;
delete temp;
}
Node* temp = head;
Node* prev = head;
while(position > 0 && temp->next != nullptr)
{
prev = temp;
temp = temp->next;
position--;
}
if(position != 0)
{
cout << "Error";
return;
}
prev->next = temp->next;
delete temp;
}
void print()
{
Node* temp = head;
while(temp != nullptr)
{
cout << temp->data << " ";
temp = temp->next;
}
}
};

int main()
{
KK* myLinkedList = new KK(1);
myLinkedList->insertNode(100);
myLinkedList->insertNode(200);
myLinkedList->insertNode(300);
myLinkedList->insertNode(400);
myLinkedList->insertNode(500);
myLinkedList->print();
cout << endl;
myLinkedList->deleteNode(300);
myLinkedList->print();
return 0;
}

9. WAP to print elements in reverse order in linked list without


disturbing the linked list.
#include <iostream>

// Structure of a node.
struct node
{
int data;
struct node* next;
node(int x)
{
data=x;
next=NULL;
}
};

void print_reverse(struct node* go)


{
if(go==NULL)
{ // If we hit the end of linked list, we return from there.
End of recursion.
return;
}
print_reverse(go->next); // Move one node forward
towards the end of linked list.
std::cout<<go->data<<" "; // While coming back from the
end of linked list, start printing the node values. Last node will be
first one in recursive stack.
}

int main()
{
// Making a linked list for testing purpose.

struct node* head = new node(100);


head->next = new node(200);
head->next->next = new node(300);
head->next->next->next = new node(400);
head->next->next->next->next = new node(500);
std::cout<<"Printing the linked list in reverse order:\n";
print_reverse(head);
return 0;

}
10. WAP to reverse a linked list
#include<iostream>

using namespace std;

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

/* Function to push nodes in a linked list. */


void push(struct node **head_ref, int data)
{
struct node *node;
node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->next = (*head_ref);
(*head_ref) = node;
}

/* Function to reverse the nodes in a linked list. */


void reverse(struct node **head_ref)
{
struct node *temp = NULL;
struct node *prev = NULL;
struct node *current = (*head_ref);
while(current != NULL)
{
temp = current->next;
current->next = prev;
prev = current;
current = temp;
}
(*head_ref) = prev;
}

/* Function to print the nodes in a linked list. */


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

/* Driver function to check the above algorithm. */


int main()
{
struct node *head = NULL;
push(&head, 100);
push(&head, 200);
push(&head, 300);
push(&head, 400);
push(&head, 500);
push(&head, 600);
cout << "List before reversing" << endl;
printnodes(head);
reverse(&head);
cout << endl;
cout << "List after reversing"<<endl;
printnodes(head);
return 0;
}
11. WAP to add two polynomials using linked list.
#include<iostream>
using namespace std;
struct Node
{
int coeff;
int pow;
struct Node *next;
};
void create_node(int x, int y, struct Node **temp)
{
struct Node *r, *z;
z = *temp;
if(z == NULL)
{
r =(struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
else
{
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}
void polyadd(struct Node *p1, struct Node *p2, struct Node *result)
{
while(p1->next && p2->next)
{
if(p1->pow > p2->pow)
{
result->pow = p1->pow;
result->coeff = p1->coeff;
p1 = p1->next;
}
else if(p1->pow < p2->pow)
{
result->pow = p2->pow;
result->coeff = p2->coeff;
p2 = p2->next;
}
else
{
result->pow = p1->pow;
result->coeff = p1->coeff+p2->coeff;
p1 = p1->next;
p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
result = result->next;
result->next = NULL;
}
while(p1->next || p2->next)
{
if(p1->next)
{
result->pow = p1->pow;
result->coeff = p1->coeff;
p1 = p1->next;
}
if(p2->next)
{
result->pow = p2->pow;
result->coeff = p2->coeff;
p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
result = result->next;
result->next = NULL;
}
}
void printpoly(struct Node *node)
{
while(node->next != NULL)
{
printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if(node->next != NULL)
printf(" + ");
}
}
int main()
{
struct Node *p1 = NULL, *p2 = NULL, *result = NULL;
create_node(100,1,&p1);
create_node(200,2,&p1);
create_node(300,3,&p1);
create_node(400,4,&p2);
create_node(500,5,&p2);
printf("Polynomial 1: ");
printpoly(p1);
printf("\nPolynomial 2: ");
printpoly(p2);
result = (struct Node *)malloc(sizeof(struct Node));
polyadd(p1, p2, result);
printf("\nPolynomial after adding p1 and p2 : ");
printpoly(result);
return 0;
}

12. WAP to implement doubly linked list.


#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *prev;
struct Node *next;
};
struct Node* head = NULL;
void insert(int newdata)
{
struct Node* newnode = (struct Node*) malloc(sizeof(struct
Node));
newnode->data = newdata;
newnode->prev = NULL;
newnode->next = head;
if(head != NULL)
head->prev = newnode ;
head = newnode;
}
void display()
{
struct Node* ptr;
ptr = head;
while(ptr != NULL)
{
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
int main()
{
insert(100);
insert(200);
insert(300);
insert(400);
insert(500);
cout<<"The doubly linked list is: ";
display();
return 0;
}

13. WAP to implement a stack using array.


#include <iostream>

using namespace std;

#define MAX 1000


class Stack
{
int top;

public:
int a[MAX];
Stack() { top = -1; }
bool push(int x);
int pop();
int peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= (MAX - 1))
{
cout << "Stack Overflow";
return false;
}
else
{
a[++top] = x;
cout << x<<endl;
return true;
}
}
int Stack::pop()
{
if (top < 0)
{
cout << "Stack Underflow";
return 0;
}
else
{
int x = a[top--];
cout<<"\n";
return x;
}
}
int Stack::peek()
{
if (top < 0)
{
cout << "Stack is Empty";
return 0;
}
else
{
int x = a[top];
return x;
}
}

bool Stack::isEmpty()
{
return (top < 0);
}
int main()
{
class Stack s;
s.push(100);
s.push(200);
s.push(300);
s.push(400);
cout << s.pop();

return 0;
}
14. WAP to implement stack using linked list.
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
node *head;
int push(int obj);
int pop();
int display();
int main()
{
char ch,c;
int del,obj,sol;
do{
cout<<"\n PUSH/INSERTION-1/n POP/DELETION-2/DISPLAY-3";
cin>>ch;
switch(ch)
{
case '1':
cout<<"\n enter element in stack";
cin>>obj;
push(obj);
break;
case '2':
del=pop();
if(del!=-1)
cout<<"\n element deleted = "<<del;
break;
case '3':
display();
break;
default:
cout<<"\n oops wrong operation\n you can try again";

}
cout<<"\n wanna try again";
cin>>c;
}while(c=='y'||c=='Y');
return 0;
}
int push(int obj)
{
node *temp;
temp=new node;
if(temp==NULL)
{
cout<<"memory not allocated";
exit(0);
}
if(head==NULL)
{
temp->next=head;
temp->data=obj;
head=temp;
}
else
{
node *trv;
trv=head;
while(trv->next!=NULL)
{
trv=trv->next;
}
trv->next=temp;
temp->data=obj;
temp->next=NULL;
}
return 0;
}
int pop()
{
if(head==NULL)
{
cout<<"\n stack is empty";
return -1;
}
else
{
node *trv,*pre;
trv=head;
while(trv->next!=NULL)
{
pre=trv;
trv=trv->next;
}
pre->next=NULL;
int temp=trv->data;
return temp;
}
}
int display()
{
if(head==NULL)
{
cout<<"\n stack is empty";
}
else
{
node *trv;
trv=head;
while(trv!=NULL)
{
cout<<trv->data<<" ";
trv=trv->next;
}
}
return 0;
}

15.
#include<stdio.h>
#include<conio.h>
#define n 5
void main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
//clrscr();
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\n Queue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
default:
printf("Wrong Choice: please see the options");
}
}
}
}

16. WAP to implement queue using linked list.


#include <iostream>
using namespace std;

struct QNode
{
int data;
QNode* next;
QNode(int d)
{
data = d;
next = NULL;
}
};

struct Queue
{
QNode *front, *rear;
Queue()
{
front = rear = NULL;
}

void enQueue(int x)
{
QNode* temp = new QNode(x);
if (rear == NULL)
{
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
void deQueue()
{
if (front == NULL)
return;
QNode* temp = front;
front = front->next;
if (front == NULL)
rear = NULL;

delete (temp);
}
};

int main()
{

Queue q;
q.enQueue(100);
q.enQueue(200);

q.deQueue();
q.enQueue(300);
q.enQueue(400);
q.enQueue(1000);
q.deQueue();
cout << "Queue Front : " << (q.front)->data << endl;
cout << "Queue Rear : " << (q.rear)->data;
return 0;
}

17. WAP to implement circular queue using arrays.

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

struct Queue
{
// Initialize front and rear
int rear, front;

// Circular Queue
int size;
int *arr;

Queue(int s)
{
front = rear = -1;
size = s;
arr = new int[s];
}

void enQueue(int value);


int deQueue();
void displayQueue();
};

/* Function to create Circular queue */


void Queue::enQueue(int value)
{
if ((front == 0 && rear == size-1) ||
(rear == (front-1)%(size-1)))
{
printf("\nQueue is Full");
return;
}
else if (front == -1) /* Insert First Element */
{
front = rear = 0;
arr[rear] = value;
}

else if (rear == size-1 && front != 0)


{
rear = 0;
arr[rear] = value;
}

else
{
rear++;
arr[rear] = value;
}
}

// Function to delete element from Circular Queue


int Queue::deQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return INT_MIN;
}

int data = arr[front];


arr[front] = -1;
if (front == rear)
{
front = -1;
rear = -1;
}
else if (front == size-1)
front = 0;
else
front++;

return data;
}

// Function displaying the elements


// of Circular Queue
void Queue::displayQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return;
}
printf("\nElements in Circular Queue are: ");
if (rear >= front)
{
for (int i = front; i <= rear; i++)
printf("%d ",arr[i]);
}
else
{
for (int i = front; i < size; i++)
printf("%d ", arr[i]);

for (int i = 0; i <= rear; i++)


printf("%d ", arr[i]);
}
}

/* Driver of the program */


int main()
{
Queue q(5);
// Inserting elements in Circular Queue
q.enQueue(100);
q.enQueue(200);
q.enQueue(300);
q.enQueue(-10);

// Display elements present in Circular Queue


q.displayQueue();

// Deleting elements from Circular Queue


printf("\nDeleted value = %d", q.deQueue());
printf("\nDeleted value = %d", q.deQueue());

q.displayQueue();

q.enQueue(1000);
q.enQueue(2000);
q.enQueue(3000);

q.displayQueue();

q.enQueue(20);
return 0;
}
18. WAP to implement priority queue using linked list.
#include <stdio.h>
#include <stdlib.h>

// Node
typedef struct node {
int data;

// Lower values indicate higher priority


int priority;

struct node* next;

} Node;

// Function to Create A New Node


Node* newNode(int d, int p)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = d;
temp->priority = p;
temp->next = NULL;

return temp;
}

// Return the value at head


int peek(Node** head)
{
return (*head)->data;
}

// Removes the element with the


// highest priority form the list
void pop(Node** head)
{
Node* temp = *head;
(*head) = (*head)->next;
free(temp);
}

// Function to push according to priority


void push(Node** head, int d, int p)
{
Node* start = (*head);
// Create new Node
Node* temp = newNode(d, p);

// Special Case: The head of list has lesser


// priority than new node. So insert new
// node before head node and change head node.
if ((*head)->priority < p) {

// Insert New Node before head


temp->next = *head;
(*head) = temp;
}
else {

// Traverse the list and find a


// position to insert new node
while (start->next != NULL &&
start->next->priority < p) {
start = start->next;
}

// Either at the ends of the list


// or at required position
temp->next = start->next;
start->next = temp;
}
}

// Function to check is list is empty


int isEmpty(Node** head)
{
return (*head) == NULL;
}

// Driver code
int main()
{
// Create a Priority Queue
// 7->4->5->6
Node* pq = newNode(500, 1);
push(&pq, 400, 2);
push(&pq, 300, 3);
push(&pq, 200, 0);

while (!isEmpty(&pq)) {
printf("%d ", peek(&pq));
pop(&pq);
}

return 0;
}

19. WAP to implement double ended queue using a linked list.


#include <iostream>

using namespace std;

// Node of a doubly linked list


struct Node
{
int data;
Node *prev, *next;
// Function to get a new node
static Node* getnode(int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = newNode->next = NULL;
return newNode;
}
};
// A structure to represent a deque
class Deque
{
Node* front;
Node* rear;
int Size;

public:
Deque()
{
front = rear = NULL;
Size = 0;
}

// Operations on Deque
void insertFront(int data);
void insertRear(int data);
void deleteFront();
void deleteRear();
int getFront();
int getRear();
int size();
bool isEmpty();
void erase();
};

// Function to check whether deque


// is empty or not
bool Deque::isEmpty()
{
return (front == NULL);
}

// Function to return the number of


// elements in the deque
int Deque::size()
{
return Size;
}

// Function to insert an element


// at the front end
void Deque::insertFront(int data)
{
Node* newNode = Node::getnode(data);
// If true then new element cannot be added
// and it is an 'Overflow' condition
if (newNode == NULL)
cout << "OverFlow\n";
else
{
// If deque is empty
if (front == NULL)
rear = front = newNode;

// Inserts node at the front end


else
{
newNode->next = front;
front->prev = newNode;
front = newNode;
}

// Increments count of elements by 1


Size++;
}
}

// Function to insert an element


// at the rear end
void Deque::insertRear(int data)
{
Node* newNode = Node::getnode(data);
// If true then new element cannot be added
// and it is an 'Overflow' condition
if (newNode == NULL)
cout << "OverFlow\n";
else
{
// If deque is empty
if (rear == NULL)
front = rear = newNode;

// Inserts node at the rear end


else
{
newNode->prev = rear;
rear->next = newNode;
rear = newNode;
}

Size++;
}
}

// Function to delete the element


// from the front end
void Deque::deleteFront()
{
// If deque is empty then
// 'Underflow' condition
if (isEmpty())
cout << "UnderFlow\n";

// Deletes the node from the front end and makes


// the adjustment in the links
else
{
Node* temp = front;
front = front->next;

// If only one element was present


if (front == NULL)
rear = NULL;
else
front->prev = NULL;
free(temp);

// Decrements count of elements by 1


Size--;
}
}

// Function to delete the element


// from the rear end
void Deque::deleteRear()
{
// If deque is empty then
// 'Underflow' condition
if (isEmpty())
cout << "UnderFlow\n";

// Deletes the node from the rear end and makes


// the adjustment in the links
else
{
Node* temp = rear;
rear = rear->prev;

// If only one element was present


if (rear == NULL)
front = NULL;
else
rear->next = NULL;
free(temp);

// Decrements count of elements by 1


Size--;
}
}

// Function to return the element


// at the front end
int Deque::getFront()
{
// If deque is empty, then returns
// garbage value
if (isEmpty())
return -1;
return front->data;
}

// Function to return the element


// at the rear end
int Deque::getRear()
{
// If deque is empty, then returns
// garbage value
if (isEmpty())
return -1;
return rear->data;
}

// Function to delete all the elements


// from Deque
void Deque::erase()
{
rear = NULL;
while (front != NULL)
{
Node* temp = front;
front = front->next;
free(temp);
}
Size = 0;
}

// Driver program to test above


int main()
{
Deque dq;
cout << "Insert element '500' at rear end\n";
dq.insertRear(500);

cout << "Insert element '100' at rear end\n";


dq.insertRear(100);

cout << "Rear end element: "


<< dq.getRear() << endl;

dq.deleteRear();
cout << "After deleting rear element new rear"
<< " is: " << dq.getRear() << endl;

cout << "Inserting element '200' at front end \n";


dq.insertFront(200);

cout << "Front end element: "


<< dq.getFront() << endl;

cout << "Number of elements in Deque: "


<< dq.size() << endl;

dq.deleteFront();
cout << "After deleting front element new "
<< "front is: " << dq.getFront() << endl;

return 0;
}

20. WAP to construct a binary tree and display its preorder,inorder


and post order traversals.
#include <iostream>
using namespace std;

/* A binary tree node has data, pointer to left child


and a pointer to right child */
struct Node
{
int data;
struct Node* left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};
/* Given a binary tree, print its nodes according to the
"bottom-up" postorder traversal. */
void printPostorder(struct Node* node)
{
if (node == NULL)
return;

// first recur on left subtree


printPostorder(node->left);

// then recur on right subtree


printPostorder(node->right);

// now deal with the node


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

/* Given a binary tree, print its nodes in inorder*/


void printInorder(struct Node* node)
{
if (node == NULL)
return;

/* first recur on left child */


printInorder(node->left);
/* then print the data of node */
cout << node->data << " ";

/* now recur on right child */


printInorder(node->right);
}

/* Given a binary tree, print its nodes in preorder*/


void printPreorder(struct Node* node)
{
if (node == NULL)
return;

/* first print data of node */


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

/* then recur on left sutree */


printPreorder(node->left);

/* now recur on right subtree */


printPreorder(node->right);
}

/* Driver program to test above functions*/


int main()
{
struct Node *root = new Node(100);
root->left = new Node(200);
root->right = new Node(300);
root->right->left = new Node(400);
root->left->right = new Node(500);

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;
}
21. WAP to construct a binary search tree.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *left, *right;
};
Node* getNode(int data)
{
Node *newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
Node *lvlOrd(Node *root , int data)
{
if(root==NULL)
{
root = getNode(data);
return root;
}
if(data <= root->data)
root->left = lvlOrd(root->left, data);
else
root->right = lvlOrd(root->right, data);
return root;
}
Node* makeTree(int arr[], int n)
{
if(n==0)
return NULL;
Node *root= NULL;
for(int i=0;i<n;i++)
root = lvlOrd(root , arr[i]);
return root;
}
void inord(Node* root)
{
if (!root)
return;
inord(root->left);
cout << root->data << " ";
inord(root->right);
}
int main()
{
int arr[] = {100,200,300,400,500,600,700,800,900};
int n = sizeof(arr) / sizeof(arr[0]);
Node *root = makeTree(arr, n);
cout << "Inorder Traversal: ";
inord(root);
return 0;
}

22. WAP to construct a graph.


#include <iostream>
using namespace std;
// stores adjacency list items
struct adjNode
{
int val, cost;
adjNode* next;
};
// structure to store edges
struct graphEdge
{
int start_ver, end_ver, weight;
};
class DiaGraph
{
// insert new nodes into adjacency list from given graph
adjNode* getAdjListNode(int value, int weight, adjNode* head)
{
adjNode* newNode = new adjNode;
newNode->val = value;
newNode->cost = weight;

newNode->next = head; // point new node to current head


return newNode;
}
int N; // number of nodes in the graph
public:
adjNode **head; //adjacency list as array of pointers
// Constructor
DiaGraph(graphEdge edges[], int n, int N)
{
// allocate new node
head = new adjNode*[N]();
this->N = N;
// initialize head pointer for all vertices
for (int i = 0; i < N; ++i)
head[i] = nullptr;
// construct directed graph by adding edges to it
for (unsigned i = 0; i < n; i++)
{
int start_ver = edges[i].start_ver;
int end_ver = edges[i].end_ver;
int weight = edges[i].weight;
// insert in the beginning
adjNode* newNode = getAdjListNode(end_ver, weight,
head[start_ver]);

// point head pointer to new node


head[start_ver] = newNode;
}
}
// Destructor
~DiaGraph()
{
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
};
// print all adjacent vertices of given vertex
void display_AdjList(adjNode* ptr, int i)
{
while (ptr != nullptr)
{
cout << "(" << i << ", " << ptr->val
<< ", " << ptr->cost << ") \n";
ptr = ptr->next;
}
}
// graph implementation
int main()
{
// graph edges array.
graphEdge edges[] =
{
// (x, y, w) -> edge from x to y with weight w
{0,1,2},{0,2,4},{1,4,3},{2,3,2},{3,1,4},{4,3,3}
};
int N = 6; // Number of vertices in the graph
// calculate number of edges
int n = sizeof(edges)/sizeof(edges[0]);
// construct graph
DiaGraph diagraph(edges, n, N);
// print adjacency list representation of graph
cout<<"Graph adjacency list "<<endl;
for (int i = 0; i < N; i++)
{
// display adjacent vertices of vertex i
display_AdjList(diagraph.head[i], i);
}
return 0;
}

23. WAP to calculate the distance between two vertices in a graph.

#include <bits/stdc++.h>
using namespace std;
// Function to calculate distance
float distance(int x1, int y1, int x2, int y2)
{
// Calculating distance
return sqrt(pow(x2 - x1, 2) +
pow(y2 - y1, 2) * 1.0);
}

// Drivers Code
int main()
{
cout << distance(3, 4, 4, 3);
return 0;
}

25.WAP to construct a minimal spanning tree of a graph.


#include <iostream>
using namespace std;

// a structure to represent a weighted edge in graph


class Edge
{
public:
int src, dest, weight;
};

// a structure to represent a connected, undirected


// and weighted graph
class Graph
{
public:
// V-> Number of vertices, E-> Number of edges
int V, E;

// graph is represented as an array of edges.


// Since the graph is undirected, the edge
// from src to dest is also edge from dest
// to src. Both are counted as 1 edge here.
Edge* edge;
};

// Creates a graph with V vertices and E edges


Graph* createGraph(int V, int E)
{
Graph* graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];

return graph;
}

// A structure to represent a subset for union-find


class subset
{
public:
int parent;
int rank;
};

// A utility function to find set of an element i


// (uses path compression technique)
int find(subset subsets[], int i)
{
// find root and make root as parent of i
// (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);

return subsets[i].parent;
}

// A function that does union of two sets of x and y


// (uses union by rank)
void Union(subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);

// Attach smaller rank tree under root of high


// rank tree (Union by Rank)
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;

// If ranks are same, then make one as root and


// increment its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// Compare two edges according to their weights.
// Used in qsort() for sorting an array of edges
int myComp(const void* a, const void* b)
{
Edge* a1 = (Edge*)a;
Edge* b1 = (Edge*)b;
return a1->weight > b1->weight;
}

// The main function to construct MST using Kruskal's algorithm


void KruskalMST(Graph* graph)
{
int V = graph->V;
Edge result[V]; // Tnis will store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges

// Step 1: Sort all the edges in non-decreasing


// order of their weight. If we are not allowed to
// change the given graph, we can create a copy of
// array of edges
qsort(graph->edge, graph->E, sizeof(graph->edge[0]),
myComp);
// Allocate memory for creating V ssubsets
subset *subsets = new subset[( V * sizeof(subset) )];

// Create V subsets with single elements


for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}

// Number of edges to be taken is equal to V-1


while (e < V - 1 && i < graph->E)
{
// Step 2: Pick the smallest edge. And increment
// the index for next iteration
Edge next_edge = graph->edge[i++];

int x = find(subsets, next_edge.src);


int y = find(subsets, next_edge.dest);

// If including this edge does't cause cycle,


// include it in result and increment the index
// of result for next edge
if (x != y)
{
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}

// print the contents of result[] to display the


// built MST
cout<<"Following are the edges in the constructed MST\n";
for (i = 0; i < e; ++i)
cout<<result[i].src<<" -- "<<result[i].dest<<" ==
"<<result[i].weight<<endl;
return;
}

// Driver code
int main()
{
/* Let us create following weighted graph
10
0--------1
|\|
6| 5\ |15
|\|
2--------3
4 */
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
Graph* graph = createGraph(V, E);

// add edge 0-1


graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = 10;

// add edge 0-2


graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 6;

// add edge 0-3


graph->edge[2].src = 0;
graph->edge[2].dest = 3;
graph->edge[2].weight = 5;
// add edge 1-3
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 15;

// add edge 2-3


graph->edge[4].src = 2;
graph->edge[4].dest = 3;
graph->edge[4].weight = 4;

KruskalMST(graph);

return 0;
}

You might also like