Laboratory Mannual
Laboratory Mannual
(ECE181512)
LAB MANUAL
FOR B.E. E&T, V-SEMESTER
Prepared by:
Dr. Mukut Senapati
Asst. Prof., E&TE Dept.
A: 7, 5, 3, 1, 20
B: 6, 25, 32, 11, 9
Write a function to combine the two lists such that the resulting list contains nodes in the
following elements:
7, 6, 5, 25, 3, 32, 1, 11, 20, 9
14 Write a program to add two polynomial using linked list. You are not allowed to create any
additional node while writing the addition function.
15 Write a program to merge two sorted linked list, restricting common elements to occur only
once only.
16 Write a program to delete the minimum value from a linked list.
17 Write a program to remove a specified node from a given Doubly Linked List and insert it at the
end of the list.
18 Write a program to split a linked list in such a way that one list will have odd position elements
and other will have even position elements. Starting position is one.
19 Write a program to reverse a string using stack and implement the stack using linked list.
20 Write a program to generate a random matrix of 0’s and 1’s of order 4×4 and run the program
for four times and draw all the four graphs.
21 Write a program to sort some words using linked list.
22 Write a program to sort some three digits number by comparing the leftmost to rightmost digit.
Codes:
#include <stdio.h>
int stack[100],i,j,choice=0,n,top=-1;
void push();
void pop();
void show();
void main ()
{
printf("Enter the number of elements in the stack ");
scanf("%d",&n);
printf("*********Stack operations using array*********");
printf("\n----------------------------------------------\n");
while(choice != 4)
{
printf("Chose one from the below options...\n");
printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
printf("\n Enter your choice \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
show();
break;
}
case 4:
{
printf("Exiting....");
break;
}
default:
{
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
if (top == n )
printf("\n Overflow");
else
{
printf("Enter the value?");
scanf("%d",&val);
top = top +1;
stack[top] = val;
}
}
void pop ()
{
if(top == -1)
printf("Underflow");
else
top = top -1;
}
void show()
{
for (i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
if(top == -1)
{
printf("Stack is empty");
}
}
2. Write a program to implement Stack using linked list.
Codes:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
/* Create empty stack */
void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
/* Display stack elements */
void display()
{
top1 = top;
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
/* Pop Operation on stack */
void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
/* Return top element */
int topelement()
{
return(top->info);
}
/* Check if stack is empty or not */
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
/* Destroy entire stack */
void destroy()
{
top1 = top;
while (top1 != NULL)
{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
OutPut:
$ cc pgm2.c
$ a.out
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56
Enter choice : 1
Enter data : 80
Enter choice : 2
Popped value : 80
Enter choice : 3
Top element : 56
Enter choice : 1
Enter data : 78
Enter choice : 1
Enter data : 90
Enter choice : 6
90 78 56
Enter choice : 7
Stack is empty
Enter choice : 5
3. Write a program to implement a circular linked list.
Codes:
#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node
{
int e;
Position next;
};
void Display(List l)
{
printf("The list element are :: ");
Position p = l->next;
while(p != l)
{
printf("%d -> ", p->e);
p = p->next;
}
}
void main()
{
int x, pos, ch, i;
List l, l1;
l = (struct Node *) malloc(sizeof(struct Node));
l->next = l;
List p = l;
printf("CIRCULAR LINKED LIST IMPLEMENTATION OF LIST ADT\n\n");
do
{
printf("\n\n1. INSERT\t 2. DELETE\t 3. FIND\t 4. PRINT\t 5. QUIT\n\nEnter the choice
:: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
p = l;
printf("Enter the element to be inserted :: ");
scanf("%d",&x);
printf("Enter the position of the element :: ");
scanf("%d",&pos);
for(i = 1; i < pos; i++)
{
p = p->next;
}
Insert(x,l,p);
break;
case 2:
p = l;
printf("Enter the element to be deleted :: ");
scanf("%d",&x);
Delete(x,p);
break;
case 3:
p = l;
printf("Enter the element to be searched :: ");
scanf("%d",&x);
p = Find(x,p);
if(p == l)
printf("Element does not exist!!!\n");
else
printf("Element exist!!!\n");
break;
case 4:
Display(l);
break;
}
}while(ch<5);
return 0;
}
Output:
CIRCULAR LINKED LIST IMPLEMENTATION OF LIST ADT
Codes:
#include <stdio.h>
//Represent a node of the doubly linked list
struct node{
int data;
struct node *previous;
struct node *next;
};
//Represent the head and tail of the doubly linked list
struct node *head, *tail = NULL;
//addNode() will add a node to the list
void addNode(int data) {
//Create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
//If list is empty
if(head == NULL) {
//Both head and tail will point to newNode
head = tail = newNode;
//head's previous will point to NULL
head->previous = NULL;
//tail's next will point to NULL, as it is the last node of the list
tail->next = NULL;
}
else {
//newNode will be added after tail such that tail's next will point to newNode
tail->next = newNode;
//newNode's previous will point to tail
newNode->previous = tail;
//newNode will become new tail
tail = newNode;
//As it is last node, tail's next will point to NULL
tail->next = NULL;
}
}
//display() will print out the nodes of the list
void display() {
//Node current will point to head
struct node *current = head;
if(head == NULL) {
printf("List is empty\n");
return;
}
printf("Nodes of doubly linked list: \n");
while(current != NULL) {
//Prints each node by incrementing pointer.
printf("%d ", current->data);
current = current->next;
}
}
int main()
{
//Add nodes to the list
addNode(1);
addNode(2);
addNode(3);
addNode(4);
addNode(5);
return 0;
}
OutPut:
Nodes of doubly linked list:
12345
5. Write a program to implement queue using array.
Codes:
#include<stdio.h>
#define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
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("\nQueue 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;
case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}
OutPut:
Codes:
// Add the new node at the end of queue and change rear
q->rear->next = temp;
q->rear = temp;
}
q->front = q->front->next;
free(temp);
}
// Driver code
int main()
{
struct Queue* q = createQueue();
enQueue(q, 10);
enQueue(q, 20);
deQueue(q);
deQueue(q);
enQueue(q, 30);
enQueue(q, 40);
enQueue(q, 50);
deQueue(q);
printf("Queue Front : %d \n", ((q->front != NULL) ? (q->front)->key : -1));
printf("Queue Rear : %d", ((q->rear != NULL) ? (q->rear)->key : -1));
return 0;
}
Output
Queue Front : 40
Queue Rear : 50
7. Write a program to implement circular queue using linked list.
Codes:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
}*rear=NULL;
del()
{
int item;
struct node *tmp;
if( isEmpty() )
{
printf("\nQueue underflow\n");
exit(1);
}
if(rear->link==rear) /*If only one element*/
{
tmp=rear;
rear=NULL;
}
else
{
tmp=rear->link;
rear->link=rear->link->link;
}
item=tmp->info;
free(tmp);
return item;
}/*End of del()*/
int peek()
{
if( isEmpty() )
{
printf("\nQueue underflow\n");
exit(1);
}
return rear->link->info;
}/* End of peek() */
int isEmpty()
{
if( rear == NULL )
return 1;
else
return 0;
}/*End of isEmpty()*/
void display()
{
struct node *p;
if(isEmpty())
{
printf("\nQueue is empty\n");
return;
}
printf("\nQueue is :\n");
p=rear->link;
do
{
printf("%d ",p->info);
p=p->link;
}while(p!=rear->link);
printf("\n");
}/*End of display()*/
OutPut:
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
Queue is :
123
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
Deleted element is 1
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
Enter your choice : 3
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
Deleted element is 2
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
Queue is :
3
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
1.Insert
2.Delete
3.Peek
4.Display
5.Quit
Queue underflow
8. Write a program to implement a deque.
Codes:
#include <stdio.h>
#define size 5
int deque[size];
int f = -1, r = -1;
// insert_front function will insert the value from the front
void insert_front(int x)
{
if((f==0 && r==size-1) || (f==r+1))
{
printf("Overflow");
}
else if((f==-1) && (r==-1))
{
f=r=0;
deque[f]=x;
}
else if(f==0)
{
f=size-1;
deque[f]=x;
}
else
{
f=f-1;
deque[f]=x;
}
}
while(i!=r)
{
printf("%d ",deque[i]);
i=(i+1)%size;
}
printf("%d",deque[r]);
}
}
else if(f==(size-1))
{
printf("\nThe deleted element is %d", deque[f]);
f=0;
}
else
{
printf("\nThe deleted element is %d", deque[f]);
f=f+1;
}
}
}
else if(r==0)
{
printf("\nThe deleted element is %d", deque[r]);
r=size-1;
}
else
{
printf("\nThe deleted element is %d", deque[r]);
r=r-1;
}
}
int main()
{
insert_front(20);
insert_front(10);
insert_rear(30);
insert_rear(50);
insert_rear(80);
display(); // Calling the display function to retrieve the values of deque
getfront(); // Retrieve the value at front-end
getrear(); // Retrieve the value at rear-end
delete_front();
delete_rear();
display(); // calling display function to retrieve values after deletion
return 0;
}
OutPut:
9. Write a program to implement priority queue using array.
Codes:
/ C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
// Function Call to insert elements
// as per the priority
enqueue(10, 2);
enqueue(14, 4);
enqueue(16, 4);
enqueue(12, 3);
return 0;
}
Output
16
14
12
10. Write a program to implement a linked list in descending order.
Codes:
#include <stdio.h>
struct Node {
int data;
struct Node* next;
};
Node* insertNode(int key) {
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
void tailRecRevese(Node* current, Node* previous, Node** head){
if (!current->next) {
*head = current;
current->next = previous;
return;
}
Node* next = current->next;
current->next = previous;
tailRecRevese(next, current, head);
}
void tailRecReveseLL(Node** head){
if (!head)
return;
tailRecRevese(*head, NULL, head);
}
void printLinkedList(Node* head){
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("
");
}
int main(){
Node* head1 = insertNode(9);
head1->next = insertNode(32);
head1->next->next = insertNode(65);
head1->next->next->next = insertNode(10);
head1->next->next->next->next = insertNode(85);
printf("Linked list : \t");
printLinkedList(head1);
tailRecReveseLL(&head1);
printf("Reversed linked list : \t");
printLinkedList(head1);
return 0;
}
Output:
Linked list : 9 32 65 10 85
Reversed linked list : 85 10 65 32 9
11. Write a program to insert an element in a sorted linked list.
Codes:
Output:
Created Linked List
1 3 5 7 9 10
12. Write a program to sort any six integers using linked list.
Codes:
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
/* start with empty linked list */
struct Node *start = NULL;
getchar();
return 0;
}
do
{
swapped = 0;
ptr1 = start;
Output:
Codes:
// Driver code
int main()
{
struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
return 0;
}
Output:
1st Number: 5x^2+4x^1+2x^0
2nd Number: -5x^1-5x^0
Added polynomial: 5x^2-1x^1-3x^0
15. Write a program to merge two sorted linked list, restricting common elements to occur
only once only.
Codes:
#include <bits/stdc++.h>
using namespace std;
Node* b = newNode(2);
b->next = newNode(3);
b->next->next = newNode(20);
vector<int>v;
while(a!=NULL){
v.push_back(a->key);
a=a->next;
}
while(b!=NULL){
v.push_back(b->key);
b=b->next;
}
sort(v.begin(),v.end());
Node* result= newNode(-1);
Node* temp=result;
for(int i=0;i<v.size();i++){
result->next=newNode(v[i]);
result=result->next;
}
temp=temp->next;
cout<<"Resultant Merge Linked List Is :"<<endl;
while(temp!=NULL){
cout<<temp->key<<" ";
temp=temp->next;
}
return 0;
}
Output
Resultant Merge Linked List Is :
2 3 5 10 15 20 40
16. Write a program to delete the minimum value from a linked list.
Codes:
// Initialize max
struct Node* maxnode = head;
struct Node* temp;
delNodes(head);
return 0;
}
Output:
Given Linked List: 12 15 10 11 5 6 2 3
Codes:
#include <stdio.h>
#include <stdlib.h>
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
getchar();
}
Output:
Original Linked list 10 8 4 2
Modified Linked list 8
18. Write a program to split a linked list in such a way that one list will have odd position
elements and other will have even position elements. Starting position is one.
Codes:
#include <stdio.h>
#include <stdlib.h>
printf("NULL\n");
}
// Helper function to insert a new node at the beginning of the linked list
void push(struct Node** head, int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
int main(void)
{
// input keys
int keys[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int n = sizeof(keys)/sizeof(keys[0]);
rearrangeEvenOdd(&head);
printList(head);
return 0;
}
Download Run Code
Output:
2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> NULL
19. Write a program to reverse a string using stack and implement the stack using linked
list.
Codes:
reverse(str);
printf("Reversed string is %s", str);
return 0;
}
Output
Reversed string is ziuQskeeG
20. Write a program to generate a random matrix of 0’s and 1’s of order 4×4 and run the
program for four times and draw all the four graphs.
Codes:
// Driver code
int main()
{
int n = 8;
generateRandom(n);
return 0;
}
Output:
34586217
23. Write a program to implement merge sort algorithm.
Codes:
#include <stdio.h>
#include <stdlib.h>
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver code */
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
24. Write a program to implement insertion sort algorithm.
Codes:
#include <math.h>
#include <stdio.h>
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Output:
5 6 11 12 13
25. Write a program to implement bubble sort algorithm.
Codes:
#include <stdio.h>
Output:
Sorted array:
12458
26. Write a program to implement selection sort algorithm.
Codes:
#include <stdio.h>
Output
Sorted array:
11 12 22 25 64
27. Write a program to implement the Radix sort algorithm.
Codes:
#include <iostream>
using namespace std;
// Driver Code
int main()
{
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
radixsort(arr, n);
print(arr, n);
return 0;
}
Output
2 24 45 66 75 90 170 802
28. Write a program to implement the quick sort algorithm.
Codes:
#include <stdio.h>
// Driver program
int main() {
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Output
Sorted array:
1 5 7 8 9 10
29. Write a program to implement linear search and binary search.
Codes:
#include <stdio.h>
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, N, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Output
Element is present at index 3
30. Write a program to find the inorder, preorder, and postorder traversal in a binary tree.
Codes:
#include <stdio.h>
#include <stdlib.h>
return (node);
}
/* Driver code*/
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);
// Function call
printf("\nInorder traversal of binary tree is \n");
printInorder(root);
getchar();
return 0;
}
Output
Inorder traversal of binary tree is
42513
31. Write a program to implement a binary search tree.
Codes:
#include <iostream>
using namespace std;
struct Node {
int data;
Node *left;
Node *right;
};
Node* create(int item)
{
Node* node = new Node;
node->data = item;
node->left = node->right = NULL;
return node;
}
/*Inorder traversal of the tree formed*/
void inorder(Node *root)
{
if (root == NULL)
return;
inorder(root->left); //traverse left subtree
cout<< root->data << " "; //traverse root node
inorder(root->right); //traverse right subtree
}
Node* findMinimum(Node* cur) /*To find the inorder successor*/
{
while(cur->left != NULL) {
cur = cur->left;
}
return cur;
}
Node* insertion(Node* root, int item) /*Insert a node*/
{
if (root == NULL)
return create(item); /*return new node if tree is empty*/
if (item < root->data)
root->left = insertion(root->left, item);
else
root->right = insertion(root->right, item);
return root;
}
void search(Node* &cur, int item, Node* &parent)
{
while (cur != NULL && cur->data != item)
{
parent = cur;
if (item < cur->data)
cur = cur->left;
else
cur = cur->right;
}
}
void deletion(Node*& root, int item) /*function to delete a node*/
{
Node* parent = NULL;
Node* cur = root;
search(cur, item, parent); /*find the node to be deleted*/
if (cur == NULL)
return;
if (cur->left == NULL && cur->right == NULL) /*When node has no children*/
{
if (cur != root)
{
if (parent->left == cur)
parent->left = NULL;
else
parent->right = NULL;
}
else
root = NULL;
free(cur);
}
else if (cur->left && cur->right)
{
Node* succ = findMinimum(cur->right);
int val = succ->data;
deletion(root, succ->data);
cur->data = val;
}
else
{
Node* child = (cur->left)? cur->left: cur->right;
if (cur != root)
{
if (cur == parent->left)
parent->left = child;
else
parent->right = child;
}
else
root = child;
free(cur);
}
}
int main()
{
Node* root = NULL;
root = insertion(root, 45);
root = insertion(root, 30);
root = insertion(root, 50);
root = insertion(root, 25);
root = insertion(root, 35);
root = insertion(root, 45);
root = insertion(root, 60);
root = insertion(root, 4);
printf("The inorder traversal of the given binary tree is - \n");
inorder(root);
deletion(root, 25);
printf("\nAfter deleting node 25, the inorder traversal of the given binary tree is - \n");
inorder(root);
insertion(root, 2);
printf("\nAfter inserting node 2, the inorder traversal of the given binary tree is - \n");
inorder(root);
return 0;
}
Output
After the execution of the above code, the output will be –
32. Write a program to convert an infix expression to postfix expression.
Codes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function call
char* postfix = infixToPostfix(infix);
printf("%s\n", postfix);
free(postfix);
return 0;
}
Output
abcd^e-fgh*+^*+i-
33. Write a program to convert an infix expression to prefix expression.
Codes:
#include <stdio.h>
#include <string.h>
#include <conio.h>
/* Global Declarations */
int pos = 0;
int top;
int length;
char symbol;
char temp;
char s[30];
char infix;
char prefix;
char pop ()
{
char item;
item = s[top];
top = top-1;
return item;
}
int G (char symbol)
{
switch (symbol)
{
case '+':
case '-': return 2;
case '*':
case '/': return 4;
case '^':
case '$': return 5;
case '(': return 0;
case ')': return 9;
default : return 7;
}
}
int F (char symbol)
{
switch (symbol)
{
case '+':
case '-': return 1;
case '*':
case '/': return 3;
case '^':
case '$': return 6;
case '(': return 0;
case '#': return -1;
default : return 8;
}
}
case '(':
temp = pop();
while( temp != ')')
{
prefix[pos] = temp;
pos--;
temp = pop();
}
if (temp != ')')
{
prefix[pos--] = pop();
}
break;
case '+':
case '-':
case '*':
case '$':
case '/':
case '^': while(F(s[top]) >= G(symbol))
{
temp = pop();
prefix[pos] = temp;
pos--;
}
push(symbol);
break;
default:
prefix[pos--] = symbol;
break;
}
length--;
{
while(s[] != '#')
{
temp = pop();
prefix[pos--] = temp;
}
for (i = 0; i < t1; i++)
{
prefix[i] = prefix[i + pos + 1];
}
/* MAIN PROGRAM */
void main ()
{
clrscr();
printf("Enter the valid infix expression\n');
scanf("%s",infix);
infix_prefix(infix, prefix);
printf("The prefix expression \n");
printf("%s\n",prefix);
getch();
}
Output
*+ABC
34. Write a program to convert to evaluate a postfix expression.
Codes:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Stack type
struct Stack {
int top;
unsigned capacity;
int* array;
};
// Stack Operations
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack
= (struct Stack*)malloc(sizeof(struct Stack));
if (!stack)
return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array
= (int*)malloc(stack->capacity * sizeof(int));
if (!stack->array)
return NULL;
return stack;
}
// Driver code
int main()
{
char exp[] = "231*+9-";
// Function call
printf("postfix evaluation: %d", evaluatePostfix(exp));
return 0;
}
Output
postfix evaluation: -4
35. Write a program using stack to convert decimal to binary, octal, and hexadecimal
number system.
Codes:
#include<stdio.h>
void convert(int, int);
int main()
{
int num;
printf("Enter a positive decimal number : ");
scanf("%d", &num);
printf("\nBinary number :: ");
convert(num, 2);
printf("\n");
printf("\nOctal number :: ");
convert(num, 8);
printf("\n");
printf("\nHexadecimal number :: ");
convert(num, 16);
printf("\n");
return 0;
}/*End of main()*/
if(num==0)
return;
convert(num/base, base);
OUTPUT:
//----------------------OUTPUT ::---------------------------------
Octal number :: 17
Hexadecimal number :: F
Codes:
#include <stdio.h>
#include <stdlib.h>
#define bool int
// Driver code
int main()
{
char exp[100] = "{()}[]";
// Function call
if (areBracketsBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
if (new_node == NULL) {
printf("Stack overflow n");
getchar();
exit(0);
}
Output
Balanced
37. Write a program to implement Breadth First Search (BFS) in a graph.
Codes:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
// This struct represents a directed graph using
// adjacency list representation
typedef struct Graph_t {
int V; // No. of vertices
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
// Constructor
Graph* Graph_create(int V)
{
Graph* g = malloc(sizeof(Graph));
g->V = V;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
g->adj[i][j] = false;
}
}
return g;
}
// Destructor
void Graph_destroy(Graph* g) { free(g); }
// function to add an edge to graph
void Graph_addEdge(Graph* g, int v, int w)
{
g->adj[v][w] = true; // Add w to v’s list.
}
// prints BFS traversal from a given source s
void Graph_BFS(Graph* g, int s)
{
// Mark all the vertices as not visited
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++) {
visited[i] = false;
}
// Create a queue for BFS
int queue[MAX_VERTICES];
int front = 0, rear = 0;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue[rear++] = s;
while (front != rear) {
// Dequeue a vertex from queue and print it
s = queue[front++];
printf("%d ", s);
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (int adjacent = 0; adjacent < g->V;
adjacent++) {
if (g->adj[s][adjacent] && !visited[adjacent]) {
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}
// Driver program to test methods of graph struct
int main()
{
// Create a graph given in the above diagram
Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
printf("Following is Breadth First Traversal "
"(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
}
Output
Following is Breadth First Traversal (starting from vertex 2)
2031
38. Write a program to implement Depth First Search (DFS) in a graph.
Codes:
#include <bits/stdc++.h>
using namespace std;
// Graph class represents a directed graph
// using adjacency list representation
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;
// function to add an edge to graph
void addEdge(int v, int w);
// DFS traversal of the vertices
// reachable from v
void DFS(int v);
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::DFS(int v)
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " ";
// Recur for all the vertices adjacent
// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}
// Driver's code
int main()
{
// Create a graph given in the above diagram
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";
// Function call
g.DFS(2);
return 0;
}
// improved by Vishnudev C
Output
Following is Depth First Traversal (starting from vertex 2)
2013
39. Write a program to implement linear probing to insert a set of integers using the hash
function k mod m in a hash table, where k is the key value and m is the size of hash table.
(hash table size should be at least the size of the array).
Codes:
#include <bits/stdc++.h>
using namespace std;
// template for generic type
template <typename K, typename V>
// Hashnode class
class HashNode {
public:
V value;
K key;
// Constructor of hashnode
HashNode(K key, V value)
{
this->value = value;
this->key = key;
}
};
// template for generic type
template <typename K, typename V>
// Our own Hashmap class
class HashMap {
// hash element array
HashNode<K, V>** arr;
int capacity;
// current size
int size;
// dummy node
HashNode<K, V>* dummy;
public:
HashMap()
{
// Initial capacity of hash array
capacity = 20;
size = 0;
arr = new HashNode<K, V>*[capacity];
return 0;
}
Output
key = 1 value = 1
key = 2 value = 3
2
3
1
0
0
40. Write a program to implement quadratic probing to insert a set of integers using the
hash function k mod m in a hash table, where k is the key value and m is the size of hash
table. (hash table size should be at least the size of the array)
Codes:
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
int arr[] = { 50, 700, 76, 85, 92, 73, 101 };
int N = 7;
// Function call
hashing(hash_table, L, arr, N);
return 0;
}
Output
700 50 85 73 101 92 76