Data Stuctures
Data Stuctures
Data Stuctures
COURSE INSTRUCTORS:
Pre-lab
The Pre-lab exercise is a homework assignment that links the lecture with the laboratory period -
typically takes 2 hours to complete. The goal is to synthesize the information they learn in lecture
with material from their textbook to produce a working piece of software. Pre-lab Students attending a
two-hour closed laboratory are expected to make a good-faith effort to complete the Pre-lab exercise
before coming to the lab. Their work need not be perfect, but their effort must be real (roughly 80
percent correct).
In-lab
The In-lab section takes place during the actual laboratory period. The First hour of the laboratory
period can be used to resolve any problems the students might have experienced in completing the
Pre-lab exercises. The intent is to give constructive feedback so that students leave the lab with
working Pre-lab software - a significant accomplishment on their part. During the second hour,
students complete the In-lab exercise to reinforce the concepts learned in the Pre-lab. Students leave
the lab having received feedback on their Pre-lab and In-lab work.
Post-lab
The last phase of each laboratory is a homework assignment that is done following the laboratory
period. In the Post-lab, students analyze the efficiency or utility of a given system call. Each Post-lab
exercise should take roughly 30 minutes to complete.
List of Experiments supposed to finish in Open Lab Sessions:-
https://www.hackerrank.com/contests/17cs1102/challenges/1-a-linear-search
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%ld",&a[i]);
int ele;
scanf("%d",&ele);
for(int i=0;i<n;i++)
if(a[i]==ele)
printf("%d",i);
break;
Output:
5
21364
3
2
1 b) Binary Search-Iterative
https://www.hackerrank.com/contests/17cs1102/challenges/1-b-binary-search-iterative
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int find(long int ele, long int a, long int b, long int arr[])
long int m;
if(a<=b)
m=(a+b)/2;
if(arr[m]==ele)
return 1;
if(arr[m]<ele)
return find(ele,m+1,b,arr);
return 0;
int main()
scanf("%ld%ld",&n,&q);
scanf("%ld",&ele);
if(find(ele,0,n-1,a)==1)
printf("YES\n");
else
printf("NO\n");
Input:
10 15 20 25 30
10
15
20
35
50
Output:
YES
YES
YES
NO
NO
1. C) Binary Search-Recursive
https://www.hackerrank.com/contests/17cs1102/challenges/1-c-binary-search-recursion/problem
Answer:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
if(arr[m]<ele)
return find(ele,m+1,b,arr);
return 0;
int main()
scanf("%ld%ld",&n,&q);
scanf("%ld",&a[i]);
scanf("%ld",&ele);
if(find(ele,0,n-1,a)==1)
printf("YES\n");
else
printf("NO\n");
}
Input:
10 15 20 25 30
10
15
20
35
50
Output:
YES
YES
YES
NO
NO
2.a) Maximum Subsequence Sum-Cubic time
https://www.hackerrank.com/contests/17cs1102/challenges/2a-maximum-subsequence-sum-in-cubic-
time
int find(long int ele, long int a, long int b, long int arr[])
long int m;
if(a<=b)
m=(a+b)/2;
if(arr[m]==ele)
return 1;
MaxSum = 0;
ThisSum = 0;
ThisSum += A[ k ];
MaxSum = ThisSum;
return MaxSum;
int main()
{
long int n,i;
scanf("%ld",&n);
for(i=0;i<n;i++)
scanf("%ld",&a[i]);
printf("%ld",MaxSubsequenceSum(a,n));
Input:
-1 3 2 10 1
Output:
16
2 b) Maximum Subsequence Sum-Logarithmic-time
https://www.hackerrank.com/contests/17cs1102/challenges/2b-maximum-subsequence-sum-in-
logarithmic-time
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
long int
int Center, i;
return A[ Left ];
else
return 0;
MaxLeftBorderSum = 0; LeftBorderSum = 0;
for( i = Center; i >= Left; i-- )
LeftBorderSum += A[ i ];
MaxLeftBorderSum = LeftBorderSum;
MaxRightBorderSum = 0; RightBorderSum = 0;
RightBorderSum += A[ i ];
MaxRightBorderSum = RightBorderSum;
MaxLeftBorderSum + MaxRightBorderSum );
long int
return MaxSubSum( A, 0, N - 1 );
int main()
for(i=0;i<n;i++)
scanf("%ld",&a[i]);
printf("%ld",MaxSubsequenceSum(a,n));
Input:
10
511
2C) Maximum Subsequence sum in Linear time
https://www.hackerrank.com/contests/17cs1102/challenges/2c-maximum-subsequence-sum-in-
linear-time
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
ThisSum = MaxSum = 0;
ThisSum += A[ j ];
MaxSum = ThisSum;
ThisSum = 0;
return MaxSum;
int main()
for(i=0;i<n;i++)
scanf("%ld",&a[i]);
printf("%ld",MaxSubsequenceSum(a,n));
Input:
4 -3 5 -2 -1 2 6 -2
Output:
11
3 a) Insertion Sort
https://www.hackerrank.com/contests/17cs1102/challenges/3-a-implement-insertion-sort
int main()
int n,i,j,k,key;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
key=a[i];
for(j=i-1;j>=0;j--)
if(key<a[j])
a[j+1]=a[j];
else
break;
a[j+1]=key;
for(k=0;k<n;k++)
printf("%d ",a[k]);
printf("\n");
}
Input:
10
-10 9 1 8 2 -9 -3 5 24 -99
Output:
-10 9 1 8 2 -9 -3 5 24 -99
-10 9 1 8 2 -9 -3 5 24 -99
-10 1 9 8 2 -9 -3 5 24 -99
-10 1 8 9 2 -9 -3 5 24 -99
-10 1 2 8 9 -9 -3 5 24 -99
-10 -9 1 2 8 9 -3 5 24 -99
-10 -9 -3 1 2 8 9 5 24 -99
-10 -9 -3 1 2 5 8 9 24 -99
-10 -9 -3 1 2 5 8 9 24 -99
-99 -10 -9 -3 1 2 5 8 9 24
b) Shell Sort
https://www.hackerrank.com/contests/17cs1102/challenges/3b-implement-shell-sort
int p,i,temp,j,k;
for (i = p; i < n; i += 1)
temp = arr[i];
arr[j] = temp;
printf("%d ",arr[k]);
printf("\n");
return 0;
int main()
int n,i;
scanf("%d",&n);
int arr[n];
shellSort(arr, n);
return 0;
Input:
10
10 9 8 7 6 5 4 3 2 1
Output:
5 9 8 7 6 10 4 3 2 1
5 4 8 7 6 10 9 3 2 1
5 4 3 7 6 10 9 8 2 1
5 4 3 2 6 10 9 8 7 1
5 4 3 2 1 10 9 8 7 6
3 4 5 2 1 10 9 8 7 6
3 2 5 4 1 10 9 8 7 6
1 2 3 4 5 10 9 8 7 6
1 2 3 4 5 10 9 8 7 6
1 2 3 4 5 10 9 8 7 6
1 2 3 4 5 8 9 10 7 6
1 2 3 4 5 8 7 10 9 6
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
C) Selection Sort
https://www.hackerrank.com/contests/17cs1102/challenges/3c-implement-selection-sort
int main()
int n,i,j,k,min;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
min=i;
for(j=i+1;j<n;j++)
if(a[min]>a[j])
min=j;
a[i]=(a[i]+a[min])-(a[min]=a[i]);
for(k=0;k<n;k++)
printf("%d ",a[k]);
printf("\n");
Input:
10 5 8 9 20
Output:
5 8 9 10 20
4 a) Quick Sort
#include<stdio.h>
int main()
int x[20],size,i;
scanf("%d",&size);
for(i=0;i<size;i++)
scanf("%d",&x[i]);
quicksort(x,0,size-1);
for(i=0;i<size;i++)
printf(" %d",x[i]);
return 0;
int pivot,j,temp,i;
if(first<last)
pivot=first;
i=first;
j=last;
while(i<j)
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j)
temp=x[i];
x[i]=x[j];
x[j]=temp;
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
Input:
100 23 45 24 37 78 90 1 7 33 11 29
Output:
1 11 23 24 29 33 37 45 71 78 90 100
4 b)Quick Sort with median of three and cut-off 3
#include <stdlib.h>
#include <stdio.h>
#define Cutoff ( 3 )
void
*Lhs = *Rhs;
*Rhs = Tmp;
int
void
int j, P;
int Tmp;
/* 2*/ Tmp = A[ P ];
/* 4*/ A[ j ] = A[ j - 1 ];
/* 5*/ A[ j ] = Tmp;
void
int i, j;
int Pivot;
/* 4*/ for( ; ; )
else
/* 9*/ break;
/* END */
main( )
int i;
int A[12]={100,23,45,24,37,78,90,1,71,33,11,29};
Qsort( A, 0,11);
printf("\t%d",A[i]);
Output:
1 11 23 24 29 33 37 45 71 78 90 100
4 c) Merge Sort
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void
int i,leftEnd,NumElements,TmpPos;
LeftEnd=Rpos-1;
TmpPos=Lpos;
NumElements=RightEnd-Lpos+1;
if(A[Lpos]<=A[Rpos])
TmpArray[TmpPos++]=A[Lpos++];
else
TmpArray [TmpPos++]=A[Rpos++];
while(Lpos<=LeftEnd)
TmpArray[TmpPos++]=A[Lpos++];
while(Rpos<=RightEnd)
TmpArray[TmpPos++]=A[Rpos++];
for(i=0;i<NumElements;i++,RightEnd--)
A[RightEnd]=TmpArray[RightEnd];
int center;
if(Left<Right)
{
center=(Left+Right)/2;
Msort(A,TmpArray,Left,center);
Msort(A,TmpArray,center+1,Right)
Merge(A,TmpArray,Left,center+1,Right);
main()
int i,TmpArray[12];
int A[12]={100,23,45,24,37,78,90,1,71,33,11,29};
Msort(A,TmpArray,0,11);
for(i=0;i<12;i++)
printf(“\t %d”,A[i]);
Output:
1 11 23 24 29 33 37 45 71 78 90 100
5 a) Single Linked List with insertion, find, delete, add after, reverse, sort and display
operations Source Code
#include<stdio.h>
#include<stdlib.h>
struct node
int data;
}*head;
temp->data=num;
while(right->next != NULL)
right=right->next;
right->next =temp;
right=temp;
right->next=NULL;
temp->data=num;
if (head== NULL)
{
head=temp;
head->next=NULL;
else
temp->next=head;
head=temp;
int i;
right=head;
for(i=1;i<loc;i++)
left=right;
right=right->next;
temp->data=num;
left->next=temp;
left=temp;
left->next=right;
return;
{
int c=0;
temp=head;
if(temp==NULL)
add(num);
else
while(temp!=NULL)
if(temp->data<num)
c++;
temp=temp->next;
if(c==0)
add(num);
else if(c<count())
addafter(num,++c);
else
append(num);
temp=head;
while(temp!=NULL)
{
if(temp->data==num)
if(temp==head)
head=temp->next;
free(temp);
return 1;
else
prev->next=temp->next
free(temp);
return 1;
else
prev=temp;
temp= temp->next;
return 0;
r=head;
if(r==NULL)
{
return;
while(r!=NULL)
printf("%d ",r->data);
r=r->next;
printf("\n");
int count()
int c=0;
n=head;
while(n!=NULL)
n=n->next;
c++;
return c;
void main()
int i,num;
head=NULL;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Size\n");
printf("4.Delete\n");
printf("5.Exit\n");
if(scanf("%d",&i)<=0){
exit(0);
else{
switch(i)
scanf("%d",&num);
insert(num);
break;
case 2: if(head==NULL)
printf("List is Empty\n");
else
}
display(n);
break;
break;
case 4: if(head==NULL)
printf("List is Empty\n");
else {
scanf("%d",&num);
if(delete(num))
else
break;
case 5: return 0;
}
5 b) Doubly Linked List with insertion, find, delete, add after, reverse, sort and display
operations Source Code
#include<malloc.h>
#include<stdio.h>
int data;
}node;
node *root,*temp,*new1;
int x;
node *creation()
scanf("%d",&x);
while(x != 999)
new1->data = x;
new1->rlink = NULL;
new1->llink = NULL;
if(root == NULL)
root = new1;
temp->rlink = new1;
new1->llink = temp;
temp = new1;
printf("Enter data");
scanf("%d",&x);
return(root);
node *temp;
temp = root;
if(temp == NULL)
printf("list is empty");
return ;
while(temp != NULL)
printf("%2d %2u->",temp->data,temp);
temp =temp->rlink;
printf("NULL");
printf("enter info");
scanf("%d",&new1->data);
new1->rlink = root;
root->llink = new1;
root = new1;
return root;
node *temp1;
int i=1,loc;
temp1 = root;
scanf("%d",&loc);
printf("enter info");
scanf("%d",&new1->data);
while(i!=loc-1)
temp1 = temp1->rlink;
i++;
new1->rlink = temp1->rlink;
new1->llink = temp1;
temp1->rlink=new1;
return root;
node *prev,*temp;
temp = root;
while(temp->rlink != NULL)
{
temp = temp->rlink;
printf("enter info");
scanf("%d",&new1->data);
temp->rlink = new1;
new1->llink = temp;
new1->rlink = NULL;
return root;
node *temp;
temp = root;
root = temp->rlink;
free(temp);
return root;
int i,loc;
temp = root;
scanf("%d",&loc);
for(i=1;i<loc;i++)
{
temp = temp->rlink;
temp->llink->rlink = temp->rlink;
temp->rlink->llink = temp->llink;
free(temp);
return root;
node *prev,*temp;
prev = root;
temp = root;
if(temp == NULL)
printf("List is empty");
return 0;
while(temp->rlink != NULL)
prev = temp;
temp = temp->rlink;
prev->rlink = NULL;
free(temp);
return root;
}
void search(node *root)
node *temp,*prev;
int item,flag=0;
temp = root;
scanf("%d",&item);
if(temp == NULL)
printf("List is empty");
while(temp->rlink != NULL)
if(temp->data == item)
flag = 1;
break;
else
temp = temp->rlink;
if(flag == 1)
else
void main()
{
node *root,*head;
int ch,ch1;
clrscr();
do
printf("\n1:creation\n2:Insert\n3:Delete\n4:Display\n5.Search");
scanf("%d",&ch);
switch(ch)
break;
case 2: clrscr();
scanf("%d",&ch1);
switch(ch1)
break;
break;
break;
}break;
case 3: clrscr();
printf("1:Delete at first\n2:Delete at given location\n3:Delete at last");
scanf("%d",&ch1);
switch(ch1)
break;
break;
break;
}break;
case 4: display(root);
break;
case 5: search(root);
break;
}while(ch<=5);
getch();
}
5 c) Circular Linked List with insertion, find, delete, add after, reverse, sort and
display operations Source Code
#include<bits/stdc++.h>
struct Node
int data;
};
if (last != NULL)
return last;
last = temp;
if (last == NULL)
return last;
if (last == NULL)
last = temp;
return last;
if (last == NULL)
return NULL;
do
if (p ->data == item)
if (p == last)
last = temp;
return last;
p = p -> next;
return last;
if (last == NULL)
return;
do
p = p -> next;
while(p != last->next);
}
// Driven Program
int main()
traverse(last);
return 0;
}
6 a) Stack using Linked List Source code
#include <stdio.h>
#include <stdlib.h>
struct node
int info;
}*top,*top1,*temp;
int topelement();
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main()
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
while (1)
scanf("%d", &ch);
switch (ch)
case 1:
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
else
e = topelement();
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
break;
void create()
top = NULL;
void stack_count()
if (top == NULL)
top->ptr = NULL;
top->info = data;
else
temp->ptr = top;
temp->info = data;
top = temp;
count++;
void display()
top1 = top;
if (top1 == NULL)
printf("Stack is empty");
return;
{
printf("%d ", top1->info);
top1 = top1->ptr;
void pop()
top1 = top;
if (top1 == NULL)
return;
else
top1 = top1->ptr;
free(top);
top = top1;
count--;
int topelement()
return(top->info);
void empty()
{
if (top == NULL)
else
void destroy()
top1 = top;
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
free(top1);
top = NULL;
count = 0;
}
6 b) Stack using two Queues Source code
#include <stdio.h>
#include <stdlib.h>
/* Queue structure */
int *arr;
} queue_t;
/* NOTE: passing the queue object, on which we will only operate the
* queue operations.
*/
queue_insert(q, v);
}
int stack_pop(queue_t * q) {
int i, n = queue_count(q);
int removed_element;
removed_element = queue_remove(q);
queue_insert(q, removed_element);
/* same as below */
removed_element = queue_remove(q);
return removed_element;
int stack_is_empty(queue_t * q) {
return queue_is_empty(q);
int stack_count(queue_t * q) {
return queue_count(q);
return q->count;
queue_t *
queue_allocate(int n) {
queue_t *queue;
queue = malloc(sizeof(queue_t));
if (queue == NULL)
return NULL;
queue->max = n;
queue->rear = n - 1;
queue->front = n - 1;
return queue;
if (q->count == q->max)
return;
q->arr[q->rear] = v;
q->count++;
}
int queue_remove(queue_t * q) {
int retval;
if (q->count == 0)
return QUEUE_EMPTY_MAGIC;
retval = q->arr[q->front];
q->count--;
return retval;
int queue_is_empty(queue_t * q) {
/* For demo */
void queue_display(queue_t * q) {
while (elements--) {
int main(void) {
queue_t *q;
int x, select;
/* Static allocation */
q = queue_allocate(MAX);
do {
printf("\nChoice: ");
switch (select) {
case 1:
/* Pushing */
stack_push(q, x);
printf("\n\n__________________________\nCurrent Queue:\n");
queue_display(q);
break;
case 2:
/* Popping */
x = stack_pop(q);
printf("\n\n\n\n__________________________\nCurrent Queue:\n");
queue_display(q);
if (x == QUEUE_EMPTY_MAGIC)
else
printf("\n__________________________\n");
break;
case 0:
printf("\nQutting.\n");
return 0;
default:
printf("\nQutting.\n");
return 0;
} while (1);
return 0;
$ gcc StackUsingQueue.c
$ ./a.out
[1] Push
[2] Pop
[0] Exit
Choice: 1
__________________________
Current Queue:
[12],
Pushed Value: 12
__________________________
[1] Push
[2] Pop
[0] Exit
Choice: 1
__________________________
Current Queue:
[12], [53],
Pushed Value: 53
_____________________
6 c) Source Code Towers of Hanoi
#include <stdio.h>
if (n == 1)
return;
int main()
return 0;
Output
#include<bits/stdc++.h>
struct Queue
// Circular Queue
int size;
int *arr;
Queue(int s)
size = s;
int deQueue();
void displayQueue();
};
(rear == (front-1)%(size-1)))
{
printf("\nQueue is Full");
return;
front = rear = 0;
arr[rear] = value;
rear = 0;
arr[rear] = value;
else
rear++;
arr[rear] = value;
int Queue::deQueue()
if (front == -1)
{
printf("\nQueue is Empty");
return INT_MIN;
arr[front] = -1;
if (front == rear)
front = -1;
rear = -1;
front = 0;
else
front++;
return data;
// of Circular Queue
void Queue::displayQueue()
if (front == -1)
printf("\nQueue is Empty");
return;
}
printf("%d ",arr[i]);
else
int main()
Queue q(5);
q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);
// Display elements present in Circular Queue
q.displayQueue();
q.displayQueue();
q.enQueue(9);
q.enQueue(20);
q.enQueue(5);
q.displayQueue();
q.enQueue(20);
return 0;
Output:
Deleted value = 14
Deleted value = 22
Queue is Full
7 B). Queue using Linked List
#include <stdlib.h>
#include <stdio.h>
struct QNode
int key;
};
// The queue, front stores the front node of LL and rear stores ths
// last node of LL
struct Queue
};
temp->key = k;
temp->next = NULL;
return temp;
}
// A utility function to create an empty queue
return q;
if (q->rear == NULL)
return;
// Add the new node at the end of queue and change rear
q->rear->next = temp;
q->rear = temp;
if (q->front == NULL)
return NULL;
q->front = q->front->next;
if (q->front == NULL)
q->rear = NULL;
return temp;
int main()
enQueue(q, 10);
enQueue(q, 20);
deQueue(q);
deQueue(q);
enQueue(q, 30);
enQueue(q, 40);
enQueue(q, 50);
return 0;
Output:
Dequeued item is 30
7 C. Queue using two stacks
#include <stdio.h>
#include <stdlib.h>
struct node
int data;
};
struct queue
};
push(&q->stack1, x);
int x;
printf("queue is empty");
return;
if (q->stack2 == NULL) {
while (q->stack1 != NULL) {
x = pop(&q->stack1);
push(&q->stack2, x);
x = pop(&q->stack2);
printf("%d\n", x);
if (newnode == NULL) {
return;
newnode->data = data;
newnode->next = (*top);
(*top) = newnode;
int buff;
if (*top == NULL) {
return;
else {
t = *top;
buff = t->data;
*top = t->next;
free(t);
return buff;
printf("%d\n", top1->data);
top1 = top1->next;
printf("%d\n", top2->data);
top2 = top2->next;
int main()
int f = 0, a;
char ch = 'y';
q->stack1 = NULL;
q->stack2 = NULL;
from queue\n3.display\n4.exit\n");
scanf("%d", &f);
switch(f) {
scanf("%d", &a);
enqueue(q, a);
break;
case 2 : dequeue(q);
break;
break;
case 4 : exit(1);
break;
default : printf("invalid\n");
break;
Output
4. Exit
34
4. Exit
55
4. Exit
99
4. Exit
77
4. Exit
3
34
55
99
77
4. Exit
4. Exit
55
99
77
4. Exit
8 a) Balanced Brackets
#define max 50
void main()
char stk[max],exp[100];
int top,i;
clrscr();
top = -1;
gets(exp);
top++;
stk[top]= exp[i];
else
if ( exp[i] == ')' )
top--;
else
printf("Unbalanced exp");
exit(0);
else
if ( exp[i] == ']' )
top--;
else
printf("Unbalanced exp");
exit(0);
else
if ( exp[i] == '}' )
top--;
else
printf("Unbalanced exp");
exit(0);
} // for
if( top == -1 )
printf("Exp is balanced");
else
} // main
Output:
Exp is Balanced
8 B).Infix to Postfix
#include<stdio.h>
char stack[20];
void push(char x)
stack[++top] = x;
char pop()
if(top == -1)
return -1;
else
return stack[top--];
int priority(char x)
if(x == '(')
return 0;
return 1;
return 2;
main()
{
char exp[20];
char *e, x;
scanf("%s",exp);
e = exp;
while(*e != '\0')
if(isalnum(*e))
printf("%c",*e);
push(*e);
printf("%c", x);
else
printf("%c",pop());
push(*e);
e++;
while(top != -1)
printf("%c",pop());
}
OUTPUT:
abc*+
ab+c*da-+
8 C). Evaluation of Postfix
#include<stdio.h>
int stack[20];
void push(int x)
stack[++top] = x;
int pop()
return stack[top--];
int main()
char exp[20];
char *e;
int n1,n2,n3,num;
scanf("%s",exp);
e = exp;
while(*e != '\0')
if(isdigit(*e))
num = *e - 48;
push(num);
}
else
n1 = pop();
n2 = pop();
switch(*e)
case '+':
n3 = n1 + n2;
break;
case '-':
n3 = n2 - n1;
break;
case '*':
n3 = n1 * n2;
break;
case '/':
n3 = n2 / n1;
break;
push(n3);
}
e++;
return 0;
OUTPUT:
Enter the expression :: 245+*
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A tree node
struct Node
int data;
};
malloc(sizeof(struct Node));
node->data = data;
return(node);
// Base case
if (root == NULL)
return INT_MIN;
// Return maximum of 3 values:
res = lres;
res = rres;
return res;
// Driver program
int main(void)
struct Node*NewRoot=NULL;
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left=newNode(1);
root->left->right->right=newNode(11);
root->right->right=newNode(9);
root->right->right->left=newNode(4);
Output:
Maximum element is 11
// Base case
if (root == NULL)
return INT_MAX;
res = lres;
res = rres;
return res;
#include<stdio.h>
#include<stdlib.h>
struct node
int key;
};
temp->key = item;
return temp;
if (root != NULL)
inorder(root->left);
inorder(root->right);
}
/* A utility function to insert a new node with given key in BST */
return node;
int main()
50
/ \
30 70
/ \ / \
20 40 60 80 */
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
inorder(root);
return 0;
Output:
20
30
40
50
60
70
80
9 b)BST- Delete, Inorder, Preorder, Postorder traversal
/*
* C Program to Construct a Binary Search Tree and perform deletion, inorder traversal on it
*/
#include <stdio.h>
#include <stdlib.h>
struct btnode
int value;
void delete1();
void insert();
void delete();
void create();
int flag = 1;
void main()
int ch;
printf("\nOPERATIONS ---");
printf("6 - Exit\n");
while(1)
scanf("%d", &ch);
switch (ch)
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
exit(0);
default :
break;
void insert()
create();
if (root == NULL)
root = temp;
else
search(root);
/* To create a node */
void create()
int data;
printf("Enter data of node to be inserted : ");
scanf("%d", &data);
temp->value = data;
if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at
right */
search(t->r);
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at
left */
search(t->l);
t->l = temp;
if (root == NULL)
return;
}
if (t->l != NULL)
inorder(t->l);
if (t->r != NULL)
inorder(t->r);
void delete()
int data;
if (root == NULL)
return;
scanf("%d", &data);
t1 = root;
t2 = root;
search1(root, data);
{
if (root == NULL)
return;
if (t->l != NULL)
preorder(t->l);
if (t->r != NULL)
preorder(t->r);
if (root == NULL)
return;
if (t->l != NULL)
postorder(t->l);
if (t->r != NULL)
postorder(t->r);
if ((data>t->value))
t1 = t;
search1(t->r, data);
t1 = t;
search1(t->l, data);
else if ((data==t->value))
delete1(t);
/* To delete a node */
int k;
if (t1->l == t)
{
t1->l = NULL;
else
t1->r = NULL;
t = NULL;
free(t);
return;
if (t1 == t)
root = t->l;
t1 = root;
else if (t1->l == t)
t1->l = t->l;
else
t1->r = t->l;
}
t = NULL;
free(t);
return;
if (t1 == t)
root = t->r;
t1 = root;
else if (t1->r == t)
t1->r = t->r;
else
t1->l = t->r;
t == NULL;
free(t);
return;
t2 = root;
if (t->r != NULL)
{
k = smallest(t->r);
flag = 1;
else
k =largest(t->l);
flag = 2;
search1(root, k);
t->value = k;
t2 = t;
if (t->l != NULL)
t2 = t;
return(smallest(t->l));
else
return (t->value);
if (t->r != NULL)
t2 = t;
return(largest(t->r));
else
return(t->value);
OPERATIONS ---
3 - Inorder Traversal
4 - Preorder Traversal
5 - Postorder Traversal
6 - Exit
40
/\
/ \
20 60
/\ \
10 30 80
90
9 C.Expression tree
#include<STDIO.H>
#include<CONIO.H>
#include<MALLOC.H>
typedef struct tree
{
char data;
struct tree *left;
struct tree *right;
}*pos;
pos stack[30];
int top=-1;
pos newnode(char b)
{
pos temp;
temp=(struct tree*)malloc(sizeof(struct tree));
temp->data=b;
temp->left=NULL;
temp->right=NULL;
return(temp);
}
void push(pos temp)
{
stack[++top]=temp;
}
pos pop()
{
pos p;
p=stack[top--];
return(p);
}
void inorder(pos t)
{
if(t!=NULL)
{
inorder(t->left);
printf(“%s”,t->data);
inorder(t->right);
}
}
void preorder(pos t)
{
if(t!=NULL)
{
printf(“%s”,t->data);
preorder(t->left);
inorder(t->right);
}
}
void postorder(pos t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
printf(“%s”,t->data);
}
}
void main()
{
char a[20];pos temp,t;int j,i;
clrscr();
printf(“\nEnter the postfix expression”);
gets(a);
for(i=0;a[i]!=NULL;i++)
{
if(a[i]==’*’ || a[i]==’/’ || a[i]==’+’ || a[i]==’-')
{
temp=newnode(a[i]);
temp->right=pop();
temp->left=pop();
push(temp);
}
else
{
temp=newnode(a[i]);
push(temp);
}
}
inorder(temp);
printf(“\n”);
preorder(temp);
printf(“\n”);
postorder(temp);
getch();
}
10 a) C program to insert a node in AVL tree
#include<stdio.h>
#include<stdlib.h>
struct Node
int key;
int height;
};
if (N == NULL)
return 0;
return N->height;
/* Helper function that allocates a new node with the given key and
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
return(node);
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
return x;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
return y;
{
if (N == NULL)
return 0;
if (node == NULL)
return(newNode(key));
return node;
node->height = 1 + max(height(node->left),
height(node->right));
unbalanced */
return rightRotate(node);
return leftRotate(node);
node->left = leftRotate(node->left);
return rightRotate(node);
node->right = rightRotate(node->right);
return leftRotate(node);
return node;
}
// of the tree.
if(root != NULL)
preOrder(root->left);
preOrder(root->right);
int main()
30
/ \
20 40
/ \ \
10 25 50
*/
preOrder(root);
return 0;
}
11 a)Hash Table with chaining
#include <stdio.h>
#include<stdlib.h>
#define MAX 20
struct Employee
int employee_id;
char employee_name[45];
int employee_age;
};
struct Record
};
int main()
hash_table[count] = NULL;
while(1)
printf("5. Quit\n");
scanf("%d",&option);
switch(option)
case 1:
printf("Employee ID:\t");
scanf("%d", &employee_record.employee_id);
printf("Employee Name:\t");
scanf("%s", employee_record.employee_name);
printf("Employee Age:\t");
scanf("%d", &employee_record.employee_age);
insert(employee_record, hash_table);
break;
case 2:
scanf("%d", &key);
count = search_element(key, hash_table);
if(count == -1)
else
break;
case 3:
scanf("%d", &key);
remove_record(key, hash_table);
break;
case 4:
show(hash_table);
break;
case 5:
exit(1);
return 0;
int key, h;
struct Record *temp;
key = employee_record.employee_id;
printf("Duplicate Key\n");
return;
h = hash_function(key);
temp->data = employee_record;
temp->link = hash_table[h];
hash_table[h] = temp;
int count;
printf("\n[%3d]", count);
if(hash_table[count] != NULL)
ptr = hash_table[count];
while(ptr != NULL)
ptr=ptr->link;
}
printf("\n");
int h;
h = hash_function(key);
ptr = hash_table[h];
while(ptr != NULL)
if(ptr->data.employee_id == key)
return h;
ptr = ptr->link;
return -1;
int h;
h = hash_function(key);
if(hash_table[h]==NULL)
return;
if(hash_table[h]->data.employee_id == key)
temp = hash_table[h];
hash_table[h] = hash_table[h]->link;
free(temp);
return;
ptr = hash_table[h];
while(ptr->link != NULL)
if(ptr->link->data.employee_id == key)
temp = ptr->link;
ptr->link = temp->link;
free(temp);
return;
ptr = ptr->link;
}
11 b) Open Addressing Hash Table with Quadratic probing and rehashing.
#include<stdio.h>
include<stdlib.h>
struct item
int key;
int value;
};
/* each hash table item has a flag (status) and data (consisting of key and value) */
struct hashtable_item
int flag;
/*
*/
};
int size = 0;
void init_array()
int i;
array[i].flag = 0;
array[i].data = NULL;
int i = index;
int h = 1;
new_item->key = key;
new_item->value = value;
while (array[i].flag == 1)
if (array[i].data->key == key)
printf("\n This key is already present in hash table, hence updating it's value \n");
array[i].data->value = value;
return;
i = (i + (h * h)) % max;
h++;
if (i == index)
return;
array[i].flag = 1;
array[i].data = new_item;
int i = index;
int h = 1;
/* probing through the hash table until we reach at location where there had not been an element even
once */
while (array[i].flag != 0)
/* case where data exists at the location and its key matches to the given
key*/
array[i].flag = 2;
array[i].data = NULL;
size--;
return;
i = (i + (h * h)) % max;
h++;
if (i == index)
break;
void display()
int i;
if (array[i].flag != 1)
else
}
int size_of_hashtable()
return size;
void main()
clrscr();
init_array();
do {
Probing.\n\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert(key, value);
break;
case 2:
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
scanf("%d", &c);
}while(c == 1);
getch();
}
12 a) Build Heap
#include<iostream>
#include<climits>
class MinHeap
public:
// Constructor
MinHeap(int capacity);
void MinHeapify(int );
int extractMin();
};
MinHeap::MinHeap(int cap)
heap_size = 0;
capacity = cap;
void MinHeap::insertKey(int k)
{
if (heap_size == capacity)
return;
heap_size++;
int i = heap_size - 1;
harr[i] = k;
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
harr[i] = new_val;
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
int MinHeap::extractMin()
if (heap_size <= 0)
return INT_MAX;
if (heap_size == 1)
heap_size--;
return harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);
return root;
void MinHeap::deleteKey(int i)
{
decreaseKey(i, INT_MIN);
extractMin();
void MinHeap::MinHeapify(int i)
int l = left(i);
int r = right(i);
int smallest = i;
smallest = l;
smallest = r;
if (smallest != i)
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
*x = *y;
*y = temp;
int main()
MinHeap h(11);
h.insertKey(3);
h.insertKey(2);
h.deleteKey(1);
h.insertKey(15);
h.insertKey(5);
h.insertKey(4);
h.insertKey(45);
h.decreaseKey(2, 1);
return 0;
#include<stdio.h>
void bfs(int v) {
q[++r] = i;
if(f <= r) {
visited[q[f]] = 1;
bfs(q[f++]);
void main() {
int v;
scanf("%d", &n);
q[i] = 0;
visited[i] = 0;
for(j=1;j<=n;j++) {
scanf("%d", &a[i][j]);
}
printf("\n Enter the starting vertex:");
scanf("%d", &v);
bfs(v);
if(visited[i])
printf("%d\t", i);
else {
break;
}
13 b) Deapth first search
#include<stdio.h>
void DFS(int);
void main()
int i,j;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
13 c ) Dijkstra Algorithm
#include<stdio.h>
#include<conio.h>
#define MAX 10
int main()
int G[MAX][MAX],i,j,n,u;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++)
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
mindistance=distance[i];
nextnode=i;
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
count++;
for(i=0;i<n;i++)
if(i!=startnode)
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
14 a) Prim’s algorithm
#include<stdio.h>
#include<stdlib.h>
#define MAX 20
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
int i,j,total_cost;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
return 0;
int prims()
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
while(no_of_edges>0)
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
v=i;
min_distance=distance[i];
u=from[v];
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
distance[i]=cost[i][v];
from[i]=v;
min_cost=min_cost+cost[u][v];
return(min_cost);
Output
0 3 1 0 0 0
3 0 0 0 3 0
1 0 0 0 0 4
0 0 0 0 0 2
0 3 0 0 0 0
0 0 4 2 0 0
#include<stdio.h>
#define MAX 30
int u,v,w;
}edge;
edge data[MAX];
int n;
}edgelist;
edgelist elist;
int G[MAX][MAX],n;
edgelist spanlist;
void kruskal();
void sort();
void print();
void main()
int i,j,total_cost;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
kruskal();
print();
void kruskal()
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;
for(i=1;i<n;i++)
for(j=0;j<i;j++)
if(G[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
sort();
for(i=0;i<n;i++)
belongs[i]=i;
spanlist.n=0;
for(i=0;i<elist.n;i++)
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);
if(cno1!=cno2)
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}
int find(int belongs[],int vertexno)
return(belongs[vertexno]);
int i;
for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
void sort()
int i,j;
edge temp;
for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
void print()
int i,cost=0;
for(i=0;i<spanlist.n;i++)
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}
15 Add two Polynomial expressions
/**
* @author Swashata
*/
#include<stdio.h>
#include<stdlib.h>
/**
*/
int coeff;
int pow;
} my_poly;
/**
* The simple menu driven main function
*/
int main(void) {
int ch;
do {
my_create_poly(&poly1);
my_show_poly(poly1);
my_create_poly(&poly2);
my_show_poly(poly2);
my_show_poly(poly3);
scanf("%d", &ch);
} while (ch);
return 0;
/**
* @return void
*/
do {
printf("\nEnter Coeff:");
scanf("%d", &coeff);
tmp_node->coeff = coeff;
printf("\nEnter Pow:");
scanf("%d", &pow);
tmp_node->pow = pow;
tmp_node->next = NULL;
printf("\nContinue adding more terms to the polynomial list?(Y = 1/N = 0): ");
scanf("%d", &flag);
if(flag) {
tmp_node->next = NULL;
} while (flag);
/**
* @return void
*/
while(node != NULL) {
node = node->next;
if(node != NULL)
printf(" + ");
/**
* @return void
*/
tmp_node->next = NULL;
*result = tmp_node; //Copy the head address to the result linked list
tmp_node->pow = poly1->pow;
tmp_node->coeff = poly1->coeff;
poly1 = poly1->next;
tmp_node->pow = poly2->pow;
tmp_node->coeff = poly2->coeff;
poly2 = poly2->next;
else {
tmp_node->pow = poly1->pow;
poly1 = poly1->next;
poly2 = poly2->next;
tmp_node->next = NULL;
while(poly1 || poly2) {
//As the last while loop will not create any unnecessary node
tmp_node = tmp_node->next;
tmp_node->next = NULL;
if(poly1) {
tmp_node->pow = poly1->pow;
tmp_node->coeff = poly1->coeff;
poly1 = poly1->next;
if(poly2) {
tmp_node->pow = poly2->pow;
tmp_node->coeff = poly2->coeff;
poly2 = poly2->next;
printf("\nAddition Complete");
}
Output: