LateralEx6 To 14 Record 2
LateralEx6 To 14 Record 2
Certificate
This is a bonafide record-2 of Practical work done by the above mentioned
candidate in CS3362/ C PROGRAMMING and DATA STRUCTURES
COURSE OBJECTIVES:
To Develop Applications in C
To Implement Linear and Non Linear Data Structures To Understand Different
Operations of Search Trees
To Get Familiarized to sorting and searching algorithms
LIST OF EXPERIMENTS
1. Practice of C Programming using statements, expressions, decision making and
iterative statements.
2. Practice of C programming using Functions and Arrays
3. Implementation of C programs using Pointers and Structures
4. Implement C Programs using Files
5. Development of real time C Applications
6. Array implementation of List ADT
7. Array Implementation of Stack and Queue ADTs
8. Linked list implementation of List, Stack and Queue ADTs
9. Applications of List, Stack and Queue ADTs
10. Implementation of Binary Trees and operations of Binary Trees
11. Implementation of Binary Search Trees
12. Implementation of searching techniques
13. Implementation of Sorting Algorithms - Insertion Sort, Quick sort, merge sort
14. Implementation of Hashing – any two collision techniques
TOTAL: 45 PERIODS
Course Outcomes:
INDEX PAGE
7a Array 11
Implementation of
Stack
7b Array 15
implementation of
Queue/ circular
Queue
8a Linked List 19
Implementation of
List
8b Linked List 25
Implementation of
stack
8c Linked List 28
Implementation of
Queue
9a Applications of List- 32
Polynomial
Addition
9b Applications of 37
Stack-Balancing
parenthesis
9c Applications of 40
queue –Storing
elements according
to age
-Linked list
implementation of
Queue
9d Applications of List- 44
Polynomial
multiplication
9e Conversion of Infix 50
to Postfix
Expression
9f Evaluation of 54
Postfix expression
4
9g Palindrome using 58
Stack
9h Palindrome using 61
Queue
10 Implementation of 65
Binary Tree and its
operations
Record -2
6
Algorithm:
Initialization:
1. Initialize the total number of elements as zero
Insertion:
1. Enter the position and element.
2. Move all the elements from that position one position backward.
3. Place the element in that position.
4. Increment the total number of elements
Deletion:
1. Enter the position and element
2. Move all the elements after the position one position forward.
3. Decrement the total number of elements
Finding element
1. Enter the element-x
2. Compare the array elements from 0th index to last position with x
3. If there is a match return the index(position of the element)
4. If there is not a match return -1
Print
1. Print the elements of the array by varying running variable from 0 to
count
Make empty
1. Assign count =0
7
Program:
//Array implementation of list ADT
#include<stdio.h>
#include<conio.h>
#include<process.h>
struct listarray
{
int a[10]; // will hold the elements in the list
int count; // will hold the total number of elements in the list
};
void initial(struct listarray *l) // initially the list will be empty.
//totalnumber of elements = 0
{
l->count=0;
}
void insert(struct listarray *l,int p1,int e1) // will insert the
//element e1 in position p1
{
int i;
if(p1<0||p1>l->count+1)
{
printf("wrong position\n");
goto xy;
}
for(i=l->count-1;i>=p1;i--) // will move all the elements from
//position p1 to next position
l->a[i+1]=l->a[i]; // backword
l->a[p1]=e1; // will insert the element e1 in position p1
l->count++; // will increment the total number of elements
xy:;
}
void delete1(struct listarray *l,int p1) // will delete the element in
//position p1
{
int i;
if(p1<0||p1>=l->count)
{
printf("wrong Position\n " );
goto xy;
}
for(i=p1;i<l->count;i++) // will move all the element from p1 one
l->a[i]=l->a[i+1]; // position forward
l->count--; // will decrement the total number of elements
8
xy:;
}
void display(struct listarray *l) // will display the elements in the list
{
int i;
printf("\n The elements in the list\n");
for(i=0;i<l->count;i++)
printf("%d\t",l->a[i]); // will display the elements from
//a[0],a[1]……a[count-1]
}
int find(struct listarray *l,int e1) // will search the element in the list
{
int i;
for(i=0;i<l->count;i++) // will compare the element e1 with
//a[0],a[1]…a[count-1]
if(l->a[i]==e1) // if match return index(position)
return i;
return -1; // if no match return -1
}
void main()
{
struct listarray l1;
int choice,e,p;
clrscr();
initial(&l1);// will call the function initialize, to assign initial
//value to count
while(1) // will execute the options until exit(1) is executed
{
printf("1.insert\t2.delete\t3.Makeempty\t4.findelement
\t5.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:// will call the method insert to insert element
printf("enter the element to be inserted\n");
scanf("%d",&e);
printf("enter the position\n");
scanf("%d",&p);
insert(&l1,p,e);
printf("after insertion\n");
display(&l1);
break;
case 2: // will call method delete1 to delete element
printf("enter pos of element to be deleted\n");
9
scanf("%d",&p);
delete1(&l1,p);
printf("after deletion\n");
display(&l1);
break;
case 3:
initial(&l1); // will call method initial to make
//count=0
printf("List after makeempty\n");
display(&l1);
break;
case 4:// will call the method find to search element
printf("enter the element to be searched\n");
scanf("%d",&e);
p=find(&l1,e);
if(p!=-1)
printf("position of the
element=%d\n",p);
else
printf("element not found\n");
break;
case 5:
exit(1); // will terminate the program
} } }
Output
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice
1
enter the element to be inserted
10
enter the position
0
after insertion
Algorithm:
Initial:
Top=-1//no elements
Push:
1. Increment top
2. Store the element in the position pointed by top
Pop
1. Decrement top
2. The element already in top will be removed from the stack
Program:
//array implementation of stack
#include<stdio.h>
#include<conio.h>
#include<process.h>
#define size 10
struct stack1
{
int a[size];
int top;
};
void initial(struct stack1 *s)//initially stack is empty. Therefore top=-1
{
s->top=-1;
}
void push(struct stack1 *s,int e1)//insert the element e1 into top of the
//stack after incrementing top
{
if(s->top>=size-1)// will check the number of elements stored in stack
//exceeds maximum size
{// if true display “stack is full, otherwise proceed with insertion
printf("stack full\n");
goto xy;
}
s->top++;
12
s->a[s->top]=e1;
xy: ;
}
int pop(struct stack1 *s)// delete one element which is in the top of the
//stack and return that element
{ //by decrementing topint e1;
if(s->top<0)// if top=-1, stack is empty, therefore display “stack is
//empty”
{ // otherwise proceed with deletion
printf("stack empty\n");
e1=s->top;
goto xy;
}
e1=s->a[s->top];
s->top--;
xy: return e1;
}
void display(struct stack1 *s)//will print all the elements of the stack
{
int i;
printf("the elements of the stack\n");
for(i=0;i<=s->top;i++)
printf("%d\t",s->a[i]);
}
13
void main()
{
struct stack1 s1;
int e,choice;
initial(&s1);//will call the fn initial() to initialize stack
clrscr();
while(1)
{
printf("1.push2.pop3.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter the element to be pushed\n");
scanf("%d",&e);
push(&s1,e);//will push the element e on to the
//top of the stack
display(&s1);
break;
case 2:
e=pop(&s1);// will delete element and deleted
//element is stored in e
printf("the deleted element=%d\n",e);
display(&s1);
break;
case 3:
} exit(1);
}
}
Output:
1.push2.pop3.exit
enter your choice
1
enter the element to be pushed
10
the elements of the stack
10
1.push2.pop3.exit
enter your choice
1
enter the element to be pushed
24
the elements of the stack
10 24
14
1.push2.pop3.exit
enter your choice
1
enter the element to be pushed
56
the elements of the stack
10 24 56
1.push2.pop3.exit
enter your choice
2
the deleted element=56
the elements of the stack
10 24
1.push2.pop3.exit
enter your choice
3
Algorithm:
Initial:
Initialize rear=-1, front=0 and count=0// no elements
Enqueue- Insertion
1. check whether count=max elements, if so, queue is full and elements
cannot be inserted
2. if queue is not full, increment rear, insert the element in position rear
mod max, to avoid inserting in non-existing position
3. increment count
Dequeue – Deletion
1. check whether count=0, if so, queue is full and so elements cannot be
deleted.
2. If queue is not empty, store the element in front position in e, increment
front so that the front element will be removed from the queue
3. Decrement count
4. Return e (deleted element)
Display
1. Move a running variable from front to rear and print the elements in
thosepositions
Program:
//array implementation of queue
#include<stdio.h>
#include<conio.h>
#define max 10
struct queue
{
int front; //front will point to the position of first element
int rear;//rear will point to the position of last element
int count;// will have the total number of elements in the queue
16
int i,f;
f=q->front%max;//f will vary from front to rear
printf("elements in queue\n");
for(i=0;i<q->count;i++)
{
printf("%d\t",q->que[f]);//display the element pointed by f
f=(f+1)%max;//take modulo value while inc f to avoid non
//existing position
}
}
void main()
{
struct queue q1;
int e1,choice;
initial(&q1);// will call fn initial, to initialize count=0,
//rear=-1,front=0
clrscr();
while(1)
{
printf("1.producer 2. consumer 3.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter the element to be inserted\n");
scanf("%d",&e1);
enqueue(&q1,e1);//will call fn enqueue to add
//produced item at end
display(&q1);// queue, display the elements of
//the queue
break;
case 2:
e1=dequeue(&q1);//will call fn dequeue to
//delete (consume) front item
printf("the deleted element=%d\n",e1);
//front of the queue
display(&q1);//display the elements of the
//queue
break;
case 3:
exit(1);
}
}
}
18
Output:
Algorithm:
Initialization:
1. Initialize the total number of elements as zero
2. Initialize head as NULL
Insertion:
1. Create a node using malloc().
2. Store the element in data field.
3. Store NULL in the address field(next node address).
4. If position=0, make the newly created node as first node
5. If position !=0 move to corresponding place and change the links to
insert the newly created node
6. Increment the total number of elements
Deletion:
1. If position=0, change the head node
2. If position!=0, move to corresponding place and change the links
3. Decrement the total number of elements
Finding element
1. Enter the element-x
2. Compare the data field elements from head node to last node with x
3. If there is a match return the address
4. If there is not a match return NULL
Print
1. Print the elements of the list from head node data field to last node data
field
Make empty
1. Assign head=NULL
20
Program:
struct listlink
{
{
newnode->next=l->head;
l->head=newnode;
}
void main()
{
struct listnode *ptr;
struct listlink l1;
int choice,e,p;
clrscr();
initial(&l1);// will initialize linked list l1
while(1)
{
printf("1.insert\t2.delete\t3.Makeempty\t4.findelement\t5.exit\n");
printf("enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter the element to be inserted\n");
scanf("%d",&e);
printf("enter the position\n");
scanf("%d",&p);
insert(&l1,p,e);// will insert the node with element e
//in position p
printf("after insertion\n");
23
}
}
}
Output:
20
enter the position
1
The elements in the list10 20
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice1
enter the element to be inserted
17
enter the position
0
The elements in the list17 10 20
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice2
enter the position of the element to be deleted
0
The elements in the list10 20
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice4
enter the element to be searched
20
Address of the element=8850144
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice4
enter the element to be searched
100
element not found
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice5
Algorithm:
Stack is a collection of elements in which insertion (push operation)
and deletion (pop operation) can be done only at the top
Initial:
1. top=NULL//no nodes
Push
1. Create a node using malloc function
2. insert the element in the data field of the node
3. connect the node with the top
4. make the new node as the top node
Pop
1. Store the element in top node in a variable e1
2. Move top from its position to next node, so that the previous node
pointedby top will be deleted
3. Return e1(deleted node’s element)
Program:
//linked list implementation of stack
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct node //node contains data field(entry) and address of next node
{
int entry;
struct node *next;
};
struct stack1 // stack contains the address of top node
{
struct node *top;
};
26
while(1)
{
printf("1.push2.pop3.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{ case 1:
printf("enter the element to be pushed\n");
scanf("%d",&e);
push(&s1,e);//will call function push and enter
//the element into stack
display(&s1);
break;
case 2:
e=pop(&s1);// will call the function pop and
//delete the top most element
printf("the deleted element=%d\n",e);
display(&s1);
break;
case 3:
exit(1);//terminate the program
} } }
Output:
1.push2.pop3.exit
enter your choice
1
enter the element to be pushed
10
the elements of the stack
10
1.push2.pop3.exit
enter your choice
1
enter the element to be pushed
24
the elements of the stack
10 24
1.push2.pop3.exit
enter your choice 2
the deleted element=10
the elements of the stack
24
1.push2.pop3.exit
enter your choice 3
Result: Thus, the program to implement stack using linked list is
implemented.
28
Algorithm:
Initial
1. Front points to the first node, rear points to the last node, count
(numberof nodes)=0
Insertion:
1. Create new node using malloc function
2. Connect the new node to rear
3. Make the newly created node as rear node
4. Increment the total number of nodes
Deletion:
1. Store the element in the first node in variable e
2. Make front to point to the next node, so that the current front node will
beremoved from the list
3. Decrement total number of nodes
4. Return the deleted element which is e
Program:
void enqueue(struct queue *q,int e)//will insert the element e inside the
//queue
{
struct node *ptr;
ptr=(struct node*)malloc(sizeof(struct node));//create a node
if(ptr==NULL)// if the node is not craeted ptr will be equivalent to
//NULL
{
printf("node cannot be created\n");// Therefore print “ node
//cannot be created”
goto xy;//stop inserting
}
ptr->entry=e;//after node is created, place e in data field of node
//ptr
ptr->next=NULL;// store NULL in address field of ptr
q->count++;//increment the total number of nodes in the queue
if(q->front==NULL && q->rear==NULL)//if front, rear
//both=NULL,
{ // the newly create node is the first node
q->front=ptr;//therefore make the newly created node as
//front and also rear
q->rear=ptr;
}
else
{ // if the node is not first node
q->rear->next=ptr;// connect the already available rear to
//newly created node ptr
q->rear=ptr;// make the newly created node as rear
}
xy: ; }
30
int dequeue(struct queue *q)// will delete front node from the queue
{
int e;
if(q->count==0)//if number of nodes = 0, no nodes are available,
//deletion is //not possible
{
printf("queue is empty\n");
e=-1;
goto xy;
}
e=q->front->entry;//store the data field of the node to be deleted in e
q->front=q->front->next;// remove the node, by moving front pointer
//to next
if(q->front==NULL)// If front=NULL, all the node are deleted ,
//therefore
q->rear=NULL; // make rear also to NULL
q->count--;//decrement the total number of nodes
xy:return e;
}
void main()
{
struct queue q1;
int e1,choice;
initial(&q1);
clrscr();
while(1)
{
printf("1.producer 2. consumer 3.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{ case 1:
31
Algorithm:
1. Create two polynomials using insertion of singly linked list
2. Add the coefficients of relative exponents
3. Display the resultant polynomials
Insertion:
1. Create a node using malloc().
2. Store the element in data field.
3. Store NULL in the address field(next node address).
4. If position=0, make the newly created node as first node
5. If position !=0 move to corresponding place and change the links to
insertthe newly created node
6. Increment the total number of elements
Print
1. Print the elements of the list from head node data field to last node data
field
Program:
//polynomial addition
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct listlink
{
int count; // list contains count(total number of node struct
listnode *head; // in the list), head(will hold the address
}; // of first node)
void main()
{
struct listnode *ptr;
struct listlink l1,l2,l3;
int choice,e,p;
clrscr();
initial(&l1);// will initialize linked list l1 initial(&l2);
initial(&l3);
35
Output:
enter the first polynomial
1.insert 2.exit
enter your choice1
enter the coefficient to be inserted
10
enter the exponent
0
after insertion
Result: Thus, the program to add two polynomials using singly linked
list isexecuted and the results are verified.
37
Algorithm:
1. Read the infix expression
2. Perform the following in all the characters
a. Check whether the character is (, push it to the stack
b. Check whether the character is, pop a character from stack
3. If the stack is empty, correct number of parentheses
4. If the stack is not empty, missing) – closing parenthesis
5. During pop operation if the stack is empty, missing (- opening
parenthesis
Program:
Header file:
//linked list implementation of stack
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct node //node contains data field(entry) and address of next node
{
char entry;
struct node *next;
};
.c file
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include "stackl.h"
void main()
{
struct stack1 s1;int i;
char infix[50],c;
clrscr();
initial(&s1);// will initialize stack by using initial function
push(&s1,'$');
printf("enter the infix expression\n");
scanf("%s",infix);// read infix expression
for(i=0;infix[i]!='\0';i++)
{ if(infix[i]=='(')
push(&s1,infix[i]);
if(infix[i]==')')
{
c=pop(&s1);
if(c=='$')
{
printf("missing opening parenthesis\n");
goto xy;
}
}
}
c=pop(&s1);
if(c=='$')
printf("correct expression\n");
else
printf("missing closing parenthesis\n");
xy: ;
}
Output1:
Enter the infix expression (a+b)
Correct expression
Output2:
Enter the infix expression (a+b
Missing closing parenthesis
Output3:
Enter the infix expression a+b)
Missing opening parenthesis
Result: Thus, the program to check the parenthesis in an expression is
executedand the results are verified.
40
Algorithm:
Initial
1. Front points to the first node, rear points to the last node, count
(number of nodes) =0
Insertion:
1. Create new node using malloc function
2. Connect the new node to queue according to the priority
3. Change front, rear if necessary
4. Increment the total number of nodes
Deletion:
1. Store the element in the first node in variable e
2. Make front to point to the next node, so that the current front node will
beremoved from the list- The highest priority node will be the first
node according to insertion and it will be removed
3. Decrement total number of nodes
4. Return the deleted element which is e
{
ptr->next=q->front;
q->front=ptr;
}
prev->next=ptr;// connect the newly created node in
//between prev and ptr
ptr->next=t;
}
xy: ;
}
struct node* dequeue(struct queue *q)// will delete front node from the
//queue
{ struct node *e;
if(q->count==0)//if number of nodes = 0, no nodes are available,
//deletion is not possible
{ printf("queue is empty\n");
e=NULL;
goto xy;
}
e=q->front;//store the first node to be deleted in e
q->front=q->front->next;// remove the node, by moving front
//pointer to next available node
if(q->front==NULL)//If front=NULL, all the node are deleted,
//therefore
q->rear=NULL; // make rear also to NULL
q->count--;//decrement the total number of nodes
xy: return e;
}
void main()
{ struct queue q1;
struct node *e1;
int a1,choice;
char name1[30];
initial(&q1);
clrscr();
while(1)
{ printf("1.producer 2. consumer 3.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{ case 1:
printf("enter the element(name,age) to be
inserted\n");
scanf("%s%d",name1,&a1);
enqueue(&q1,name1,a1);// will call fn
//enqueue,insert the element e1 in the queue
display(&q1);
break;
case 2:
e1=dequeue(&q1);// will call the fn dequeue,
//delete the front node
printf("the deleted element=%s\t%d\n",e1-
>name,e1->age);
display(&q1);
break;
case 3:
exit(1);// terminate the program
} }}
Output:
1. Producer 2. Consumer 3. Exit
Enter your choice 1
Enter name, age Abc 30
After insertion
Abc 30
1. Producer 2. Consumer 3. Exit
Enter your choice 1
Enter name,age Pqr 40
After insertion Abc 30 pqr 40
1. Producer 2. Consumer 3. Exit
Enter your choice 2
After Deletion Pqr 40
1. Producer 2. Consumer 3. Exit
Enter your choice 3
Result: Thus, the program to implement priority queue is executed
44
Algorithm:
1. Create two polynomials using insertion of singly linked list
2. Add the exponents, multiply the coefficients to get resultant exponents,
coefficients.
3. Display the resultant polynomials
Insertion:
1. Create a node using malloc().
2. Store the element in data field.
3. Store NULL in the address field(next node address).
4. If position=0, make the newly created node as first node
5. If position !=0 move to corresponding place and change the links to
insertthe newly created node
6. Increment the total number of elements
Print
1. Print the elements of the list from head node data field to last nodedata
field
Program:
//polynomial multiplication
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct listnode//node contains coefficient, exponent and address of
{ // next node
int coeff;
int expo;
struct listnode *next;
};
45
struct listlink
{
int count; // list contains count(total number of node s in the list
struct listnode *head; // head(will hold the address
}; // of first node)
}
l->count++; // increment the total number of nodes
xy:;
}
void main()
{
struct listnode *ptr;
struct listlink l1,l2,l3;
int choice,e,p;
clrscr();
47
}
l3:mul(&l1,&l2,&l3);
}
Output:
enter the first polynomial
1.insert 2.exit
enter your choice1
enter the coefficient to be inserted
10
enter the exponent
0
after insertion
The elements in the list10x0
1.insert 2.exit
enter your choice1
enter the coefficient to be inserted
5
enter the exponent
1
after insertion
Algorithm:
Program:
struct node //node contains data field(entry) and address of next node
{
char entry;
struct node *next;
};
C file
#include "stack1.h"
// will return stack priority of the element in the top of the stack
int stackpri(char c)
{ //( ---- 0, * ------ 2, / ---- 2, + ----- 1, - ---- 1, $ ----- -1
int r;
switch(c)
{
case '(':
r=0;
break;
case '*':
r=2;
break;
case '/':
r=2;
break;
case '+':
r=1;
break;
case '-':
r=1;
break;
case '$':
r=-1;
break;
}
return r;
}
int inputpri(char c)// will return the input priority of the input character
{ //(--- 3, * ------- 2, / ---- 2, + ----- 1, - ------ 1
int r;
switch(c)
{
case '(':
52
r=3;
break;
case '*':
r=2;
break;
case '/':
r=2;
break;
case '+':
r=1;
break;
case '-':
r=1;
break;
}
return r;
}
void main()
{
struct stack1 s1;
int i,j=0;
char infix[50],postfix[50],c;
clrscr();
initial(&s1);// will initialize stack by using initial function
push(&s1,'$');//push $ on to the stack
printf("enter the infix expression\n");
scanf("%s",infix);// read infix expression
for(i=0;infix[i]!='\0';i++)
{
if(isoperand(infix[i]))
{
postfix[j]=infix[i];//add infix character to postfix if
//operand
j++;
}
53
else
{
if(infix[i]==')')//if infix character is ) pop stack
{
c=pop(&s1);
//until poped characted is (, add popped character to postfix exp
while(c!='(')
{
postfix[j]=c;
j++;
c=pop(&s1);
}
}
else // if infix character is not )
{
//until inputpri(input char)<= stackpri(top element)
while(inputpri(infix[i])<=stackpri(s1.top->entry))
{
c=pop(&s1);// pop stack, add to postfix exp
postfix[j]=c;
j++;
}
push(&s1,infix[i]);// push infix character to stack
}
}
}
c=pop(&s1);
while(c!='$')// pop all the remaining characters , add it to postfix exp
{
postfix[j]=c;
j++;
c=pop(&s1);
}
postfix[j]='\0';
printf("postfix expression=%s\n",postfix);
}
Output:
enter the infix expression(a+b)*c
postfix expression=ab+c*
Algorithm:
1. Read the postfix expression
2. Perform the following in each character of postfix expression
a. If character is operand push its corresponding numeric value inside the
stack
b. If character is operator, pop two top most operands from stack, perform
operation and push the result on to the stack
3. Pop the result from the stack
Program:
Stack2.h
struct node //node contains data field(entry) and address of next node
{
int entry;
struct node *next;
};
C Program:
#include "stack1.h"
#include <ctype.h>
56
void main()
{
struct stack1 s1;
int i,r,c1,c2;
char postfix[50];
clrscr();
initial(&s1);// will initialize stack by using initial function
printf("enter the postfix expression\n");
scanf("%s",postfix);// read infix expression
for(i=0;postfix[i]!='\0';i++)
{
if(!isoperator(postfix[i]))//if operand, push its value into
//stack
push(&s1,toascii(postfix[i])-toascii('0'));
else
{
// if operator, pop two operands and perform corresponding operation
c1=pop(&s1);// by using switch case
c2=pop(&s1);
switch(postfix[i])
{
case '*':
push(&s1,c2*c1);
break;
case '/':
push(&s1,c2/c1);
break;
case '+':
push(&s1,c2+c1);
break;
case '-':
push(&s1,c2-c1);
}
57
}
}
c1=pop(&s1);//pop result from stack
printf("value of postfix expression=%d",c1);
}
Output1:
Output2:
enter the postfix expression54+8-
value of postfix expression=1
Output3:
enter the postfix expression54*3+
value of postfix expression=23
Algorithm:
Program:
Stack2.h
struct node //node contains data field(entry) and address of next node
{
int entry;
struct node *next;
};
C Program:
#include"stack2.h"
#include<process.h>
void main()
{
int i,e,choice;
char str1[30],str2[30];
struct stack1 s1;
initial(&s1);//will call the fn initial() to initialize stack
clrscr();
printf("enter a string\n");
scanf("%s",str1);
printf("\ngiven string=%s\n",str1);
for(i=0;str1[i]!='\0';i++)
push(&s1,str1[i]);
for(i=0;s1.top!=NULL;i++)
str2[i]=pop(&s1);
str2[i]='\0';
printf("reversed string=%s\n",str2);
for(i=0;str1[i]!='\0';i++)
if(str1[i]!=str2[i])
{
printf("%s is not palindrome\n",str1);
exit(1);
}
printf("%s is palindrome\n",str2);
}
Output1: Output2:
enter a string enter a string
hamam liril
given string=hamam given string=liril
reversed reversed
string=mamah string=liril
hamam is not liril is palindrome
palindrome
Algorithm:
1. Create a queue with enqueue, dequeue operations
2. Enter string1
3. Insert the string in reverse order inside the queue
4. Delete the elements from the queue and store them in string2
5. Compare the elements of string1, string2
6. If equal display “palindrome”
7. If not equal display “not palindrome”
Program:
//queue1.h
#include<stdlib.h>
struct node//node contains data field(entry), address of next node
//(*next)
{
int entry;
struct node *next;
};
void initial();
void enqueue(int);
int dequeue();
void display();
xy:return e;
}
void display()
{
int i;
struct node *ptr=front;
printf("elements in queue\n");
for(i=0;i<count;i++)
{// print the data field of all nodes by moving ptr from front to last
printf("%d\t",ptr->entry);
ptr=ptr->next;
}
}
C File:
#include<stdio.h>
#include"queue1.h"
#include<process.h>
#include<string.h>
void main()
{
int i,l,e,choice;
char str1[30],str2[30];
initial();//will call the fn initial() to initialize stack
clrscr();
printf("enter a string");
scanf("%s",str1);
printf("\ngiven string=%s\n",str1);
l=strlen(str1);
for(i=l-1;i>=0;i--)
enqueue(str1[i]);
for(i=0;i<l;i++)
str2[i]=dequeue();
str2[i]='\0';
printf("reversed string=%s\n",str2);
for(i=0;str1[i]!='\0';i++)
if(str1[i]!=str2[i])
{
printf("%s is not palindrome\n",str1);
exit(1);
64
}
printf("%s is palindrome\n",str1);
}
Output:1
enter a stringtamil
given string=tamil
reversed string=limat
tamil is not palindrome
Output2:
enter a stringmalayalam
given string=malayalam
reversed string=malayalam
malayalam is palindrome
Result: Thus, the C program to find out whether the given string is
palindromeor not using queue is executed and the result is verified.
65
Algorithm:
1. Every node x, all the items in the left sub tree are smaller than the item
x,the values of all items in right sub tree are larger then item x
Initial:
1. Initialize root , root left, root right as NULL and count as zero
Make empty
1. Traverse the tree , release all nodes, make root as NULL
Find
1. If ptr=NULL return NULL, element not found
2. If element < entry in ptr traverse the tree in left
3. If element > entry in ptr , traverse the tree in right
4. If element= entry in ptr return ptr, element found
Find min
1. If ptr=NULL, return NULL, tree is NULL
2. Traverse towards left and return the leftmost node, it will hold the
smallest element because, in binary search tree
Every node x, all the items in the left sub tree are smaller than the item
x,the values of all items in right sub tree are larger then item x
Find max
1. If ptr=NULL, return NULL, tree is NULL
2. Traverse towards right and return the rightmost node, it will hold the
largest element because, in binary search tree
Every node x, all the items in the left sub tree are smaller than the item
x,the values of all items in right sub tree are larger then item x
Insertion
1. If root is NULL, make a new node with the given element e1, make its
left, right as NULL, consider it as root
2. If given e1 is < the element in already available node, traverse towards
left until an empty place can be found
3. If given e1 is > the element in already available node, traverse towards
right until an empty place can be found
67
Deletion
1. If node to be deleted is a leaf node, remove it by making its previous
linkNULL
2. If the node has one child, the node can be deleted after adjusting its
parents link to by-pass the node
3. If the node has two children, replace the data of this node with the
smallest data of the right sub tree and recursively delete that node.
Program:
//binary search tree implementation
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct node// node- entry(data field), pointers left, right, address of left
{ // sub tree , right sub tree
int entry;
struct node *left;
struct node *right;
};
struct binsearch// search tree - pointer root -hold address of root node,
{ // count , that can hold the number of nodes
struct node *root;
int count;
};
struct binsearch t;
void initial();
void makeempty(struct node*);
struct node* find(struct node*,int);
struct node* findmin(struct node*);
struct node* findmax(struct node*);
void insert(struct node*,int);
void remove1(struct node*,int);
void inorder(struct node*);
void postorder(struct node*);
void preorder(struct node*);
struct node *prev;
68
void main()
{
struct node *ptr,*r;
int choice,e;
clrscr();
initial();
while(1)
{
printf("1.insert2.remove3.makeempty4.find5.findmin6.findmax\n");
printf("7.inorder8.preorder9.postorder10.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter the element to be inserted\n");
scanf("%d",&e);
ptr=t.root;
insert(ptr,e);
t.count++;
break;
case 2:
printf("enter the element to be deleted\n");
scanf("%d",&e);
ptr=t.root;
remove1(ptr,e);
t.count--;
break;
case 3:
makeempty(t.root);
break;
case 4:
printf("enter the element to be searched\n");
scanf("%d",&e);
r=find(t.root,e);
if(r==NULL)
printf("element not found\n");
else
printf("element found in position=%ld\n",r);
break;
case 5:
r=findmin(t.root);
printf("element found in position=%ld\n",r);
69
printf("smallest element=%d\n",r->entry);
break;
case 6:
r=findmax(t.root);
printf("element found in position=%d\n");
printf("largest element=%d\n");
break;
case 7:
inorder(t.root);
break;
case 8:
preorder(t.root);
break;
case 9:
postorder(t.root);
break;
case 10:
exit(1);
}
}
}
void initial()// will initialize root, left, right as NULL, count=0
{
t.root=NULL;
t.root->left=NULL;
t.root->right=NULL;
t.count=0;
}
void makeempty(struct node *ptr1)//traverse left , right sub trees,
//release the pointer, initialize all the members of the tree
{
if(ptr1!=NULL)
{
makeempty(ptr1->left);
makeempty(ptr1->right);
free(ptr1);
}
initial();
}
70
Output:
Algorithm:
Program:
#include<stdio.h>
void main()
{
int n,a[20],pos=-1,e,i;
printf("enter n\n");
scanf("%d",&n);
printf("enter n elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the element to be searched\n");
scanf("%d",&e);
for(i=0;i<n;i++)
if(a[i]==e)
pos=i;
if(pos==-1)
printf("element not found\n");
else
printf("position of element %d=%d\n",e,pos);
Algorithm:
1. Start
2. Read n
3. Repeat for( i=0;i<n;i++)
a. Read a[i]// in ascending order
4. Read e//element to be searched
5. Assign low=0, high=n-1
6. Repeat if(low<=high)
a. mid=(low+high)/2
b. check if(e==a[mid])
Display "element found at", i
stop
c. check if(e<a[mid])
high=mid-1
d. check if(e>a[mid])
low=mid+1
7. if(low>high)
Display "element not found"
8. Stop
Program:
#include<stdio.h>
#include<process.h>
void main()
{
int i,a[20],n,e,mid,low,high;
printf("enter n\n");
scanf("%d",&n);
printf("enter n elements in ascending order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter element to be searched\n");
scanf("%d",&e);
low=0; high=n-1;
76
while(low<=high)
{
mid=(low+high)/2;
if(e==a[mid])
{
printf("%d is found at position %d\n", e,mid);
exit(1);
}
else if(e<a[mid])
high=mid-1;
else
low=mid+1;
}
printf("%d not found\n",e);
}
Output:
enter n5
enter n elements in ascending order 10 12 17 25 50
enter element to be searched 17
17 is found at position 2
enter n6
enter n elements in ascending order 1 12 27 35 57
enter element to be searched100
100 not found
Algorithm:
Function insertionsort1:
1. start
2. The dummy argument is the array a1
3. Repeat for i in range 1 and n1-1
Assign currentvalue=a1[i]
Assign position=i
Repeat while position>0 and a1[position-1]>currentvalue
Assign a1[position]=a1[position-1]
position=position-1
Assign a1[position]=currentvalue
4. return
main function:
1. Start
2. Declare array a
3. Read the total number of elements n
4. Repeat for i in range 0 and n-1
a. Read the element
b. Add the element to the list or array
5. Call insertionsort1 function
6. Display ascending order
7. Display the array
8. Display Descending order
9. Repeat for i in range n-1 and 0
Display the elements
10. Stop
Program:
#include<stdio.h>
void sort(int a1[],int n1)
{
int currentvalue,i,pos;
for (i=0;i<n1;i++)
{
currentvalue=a1[i];
pos=i;
while(pos>0 && a1[pos-1]>currentvalue)
{
78
a1[pos]=a1[pos-1];
pos=pos-1;
}
a1[pos]=currentvalue;
}
}
void main()
{
int i,a[10],n;
void sort(int[],int);
printf("enter total number of elements in arrayn\n");
scanf("%d",&n);
printf("enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,n);
printf("ascending order\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
printf("descending order\n");
for(i=n-1;i>=0;i--)
printf("%d\t",a[i]);
printf("\n");
printf("maximum=%d\n",a[n-1]);
printf("minimum=%d\n",a[0]);
printf("Second largest=%d\n",a[n-2]);
printf("Second smallest=%d\n",a[1]);
}
Output:
enter the total number of elements in the array: 5
enter the elements
5 1 4 2 3
ascending order
1 2 3 4 5
descending order
5 4 3 2 1
maximum=5
minimum=1
Second largest=4
Second smallest=2
Algorithm:
a. Quick sort is partition exchange sort
b. Divide and Conquer rule is followed in this algorithm
c. Select pivot(normally first element in the array)
d. Divide the array into two with respect to pivot , such that all the
elements smaller than the pivot are placed before pivot , all the
elements greater than pivot are placed after pivot
e. In the two partitioned array continue step 4 until all the arrays hold only
one element
Program:
//quick sort
#include<stdio.h>
int i,j,n,pivot,a[20];
void quick(int a[],int left,int right);
void swap(int a[],int i,int j);
void main()
{
int i,n,a[20];
clrscr();
while(i<j)
{
while(a[i]<=pivot && i<last)
i++;
while(a[j]>=pivot && j>first)
j--;
if(i<j)
swap(a,i,j);
}
swap(a,first,j);
quick(a,first,j-1);
quick(a,j+1,last);
}
}
void swap(int a[],int i,int j )
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Output:
enter the total number of elements:
5
enter the elements5
4
3
2
1
the sorted list
1 2 3 4 5
Result: Thus, the program to implement quick sort is executed and the
results areverified.
81
Algorithm:
1. Read the array
2. Divide the array into 2 halves repeatedly until the array size becomes 1
3. Merge the arrays by using the following steps
l1=low ( lower bound of left array)
l2= mid+1; ( lower bound of right array)
i=low ( lower bound of resultant array)
Repeat for l1<=mid and l2<=high
i. if (a[l1]<=a[l2])
b[i]=a[l1++];
ii. else
b[i]=a[l2++];
iii. Increment i
4. while (l1<=mid)
b[i++]=a[l1++];
5. while(l2 <= high)
b[i++] = a[l2++];
6. Restore array b to a
7. Stop
Program:
#include <stdio.h>
#define max 10
int a[10] = { 10, 4, 9, 26, 2, 31, 3, 5, 42, 44 };
int b[10];
void merging(int low, int mid, int high)
{
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++)
{
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high)
82
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}
Output:
Result: Thus, the program to implement Merge Sort is executed and the
result isverified.
83
Algorithm:
Program:
//Hash Table
#include<stdio.h>
#include<conio.h>
#define max 30
int h[max],n;
void main()
{
int e,hashfn(int),i;
clrscr();
printf("enter the total number of elements\n");
scanf("%d",&n);
for(i=0;i<10;i++)
h[i]=0;
printf("enter %d elements other than zero\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&e);
h[hashfn(e)]=e;
84
}
printf("the elements in hash table\n");
for(i=0;i<10;i++)
printf("%d\t",h[i]);
}
Output:
Result: Thus, the hash table is implemented and the result is verified
85
Algorithm:
1. Hash function will return a value using which the element can be
stored in the hash table, retrieved from the hash table easily. The result
of the hash function will specify the location of the element inside the
hash table
2. A simplest hash function will consider element mod total number of
elements as location of the element inside the hash table
3. Open addressing – hash tables without linked list
a. Linear probing
b. Quadratic probing
c. Double hashing
4. Linear probing- in this method the hash function will calculate the hash
value. If the position pointed by hash value is not empty in hash table
(called as collision), the function will move to the next position in the
table
5. Disadvantage of linear probing – if collision occurs, more than one
time,the function will take more than one attempt to find the position
for the element, called as primary clustering
6. Quadratic probing will avoid primary clustering. When collision
occurs, the function will move to the next position, if that position is
not empty itwill apply the function F(i)=i2
7. i represents the number of times collision occurs , starts with 2
8. Disadvantage: May miss some hash slots
Program:
#include<stdio.h>
#include<math.h>
#include<conio.h>
#define max 30
int h[max],n;
void main()
{
int e,hashfn(int),i;
clrscr();
printf("enter the total number of elements\n");
scanf("%d",&n);
for(i=0;i<10;i++)
h[i]=0;
86
Theory:
1. Hash function will return a value using which the element can be
stored in the hash table, retrieved from the hash table easily. The
result of the hash function will specify the location of the element
inside the hash table
2. A simplest hash function will consider element mod total number of
elements as location of the element inside the hash table
3. Open addressing – hash tables without linked list
- Linear probing, Quadratic probing, Double hashing
4. Linear probing- in this method the hash function will calculate the
hash value. If the position pointed by hash value is not empty in hash
table (called as collision), the function will move to the next position
in the table
5. Disadvantage of linear probing – if collision occurs, more than one
time, the function will take more than one attempt to find the position
for the element, called as primary clustering
6. Quadratic probing will avoid primary clustering. When collision
occurs, the function will move to the next position, if that position is
not empty it will apply the function F(i)=i2
7. i represents the number of times collision occurs, starts with 2
8. In Double hashing, if primary clustering occurs, the algorithm will
use a second hash function like hash2(X)=R-(X mod R), the resultant
value can be added with the previously found collided value, new
position can be calculated
9. After primary clustering, after applying the second function also, if
the algorithm takes several attempts to find the position, the situation
is called as secondary clustering
Algorithm:
Program:
#include<stdio.h>
#include<math.h>
#include<conio.h>
#define max 30
int h[max],n;
void main()
{
int e,hashfn(int),i;
clrscr();
printf("enter the total number of elements\n");
scanf("%d",&n);
for(i=0;i<10;i++)
h[i]=0;
printf("enter%d elements other than zero\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&e);
h[hashfn(e)]=e;
}
printf("the elements in hash table\n");
for(i=0;i<10;i++)
printf("%d\t",h[i]);
}
int hashfn(int e1)
{
int ht,ht1;
ht=e1%10;
ht1=ht;
while(h[ht]!=0)
{
int R=7;
ht=R-(e1%R);
ht1=ht1+ht;
ht1=ht1%10;
if(h[ht1]==0)
return ht1;
ht=ht*2;
ht=ht%10;
}
return ht;
}
89
Output:
Theory:
1. Hash function will return a value using which the element can be
stored in the hash table, retrieved from the hash table easily. The
result of the hash function will specify the location of the element
inside the hash table
2. A simplest hash function will consider element mod total number of
elements as location of the element inside the hash table
3. Open addressing – hash tables without linked list
a. Linear probing
b. Quadratic probing
c. Double hashing
4. Separate chaining – hash tables with linked list
a. Each position in the hash table will have one linked list
b. The hash value is calculated by using the simple formula:
element mod table size
c. All the elements resulting in the same hash value will be stored
continuously in the linked list in the corresponding position
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
#define max 30
int h[max][10],n;
void main()
{
int e,hashfn(int),i,j;
clrscr();
printf("enter the total number of elements\n");
scanf("%d",&n);
for(j=0;j<max;j++)
for(i=0;i<10;i++)
h[j][i]=-1;
91
Output:
enter the total number of elements
5
enter 5 elements other than zero
1 11 121 1221 2
the elements in hash table
0 1 2 0 11 1221 121 0 0 0
Algorithm:
In order traversal:
1. LVR
2. Move to left pointer until NULL
3. Display the entry
4. Move to right pointer until NULL
Program:
//construction of expression tree and traversal
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
93
struct node// node contains entry, left, right, next pointers that can
//hold the address of another node
{
char entry;
struct node *left;
struct node *right;
struct node *next;
};
struct stack1// stack contains count (number of nodes), pointer top
//that can hold the address of top most node
{
int count;
struct node *top;
};
void initial (struct stack1 *s) // will initialize count to 0, and top=
//NULL when stack contains no nodes
{
s->count=0;
s->top=NULL;
}
void push(struct stack1 *s, struct node *ptr) // will push the node ptr
// to the top of the stack
{
ptr->next=s->top;// connect ptr to top of the stack
s->top=ptr;// make the connected ptr as top
s->count++;// increment the total number of nodes
}
struct node* pop(struct stack1 *s) // will remove the top node from
//the stack, return the address of that node
{
struct node *newptr;
newptr=s->top;// store the address of topmost node in newptr
s->top=s->top->next;// move top from current node to next
s->count--;// decrement the count (total number of elements)
return newptr;// return the address of removed topmost node
}
void main()
{
int isoperator(char);
void inorder(struct node*);
void postorder(struct node*);
void preorder(struct node*);
94
newptr->left=p1;
newptr->right=p2;
newptr->next=NULL;
return newptr;
}
struct node* make(char c)
{
struct node *newptr;
newptr=(struct node*)malloc(sizeof(struct node));
newptr->entry=c;
newptr->left=NULL;
newptr->right=NULL;
newptr->next=NULL;
return newptr;
}
void inorder(struct node *ptr)//LVR
{
if(ptr->left!=NULL)// move to left pointer till NULL
inorder(ptr->left);
printf("%c\t",ptr->entry);// display the data field
if(ptr->right!=NULL)// move to right pointer till NULL
inorder(ptr->right);
}
void preorder(struct node *ptr)
{
printf("%c\t",ptr->entry);// display the data field
if(ptr->left!=NULL)// move to the left pointer till NULL
preorder(ptr->left);
if(ptr->right!=NULL)// move to the right pointer till NULL
preorder(ptr->right);
}
void postorder(struct node *ptr)
{ if(ptr->left!=NULL)// move to the left pointer till NULL
postorder(ptr->left);
if(ptr->right!=NULL)// move to the right pointer till NULL
postorder(ptr->right);
printf("%c\t",ptr->entry);// display the data field
}
Output:
Enter postfix expression 54+9*
Inorder traversal 5+4*9
Preorder traversal *+549
Postorder traversal 54+9*
Algorithm:
1. A heap is defined to be a complete binary tree with a
propertythat each node in the tree will be greater than
its children (maxheap or descending heap) and each
node in the tree will be smaller than is children (min
heap or ascending heap)
2. create_heap function will create a max heap by placing
largestelement at root and will produce the children as
per the rule ofmax heap
3. heap() function will sort the array by taking the root
(greatestelement), placing it at the end of the array ,
and moving the correct child to root , other relevant
positions
4. repeat step 3 till there are elements to be sorted
Program:
97
#include<iostream.h>
#include<conio.h>
void heap(int a[],int );
void create_heap(int a[],int );
void main()
{
int a[50],i,n;
clrscr();
printf("enter the limit:\n");
scanf(“%d”,&n);
printf("enter the elements:\n");
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
heap(a,n);
printf("\nthe sorted list:\n");
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}
void create_heap(int a[],int n)
{
int i,j,q,key;
for(q=1;q<n;q++)
{
i=q;
key=a[q];
j=(int)(i/2);
while((i>0) && (key>a[j]))
{
a[i]=a[j];
i=j;
j=(int)i/2;
if(j<0)
j=0;
}
a[i]=key;
}
printf("the created max heap\n");
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}
void heap(int a[],int n)
{
int i,j,q,key,temp;
create_heap(a,n);
for(q=n-1;q>=1;q--)
{
98
temp=a[0];
a[0]=a[q];
a[q]=temp;i=0;
key=a[0];
j=1;
if((j+1)<q)
if(a[j+1]>a[j])
j=j+1;
while((j<=(q-1)) && (a[j]>key))
{
a[i]=a[j];
i=j;
j=2*i;
if((j+1)<q) if(a[j+1]>a[j])
j=j+1;
else if(j>n-1)
j=n-1;
a[i]=key;
}
}
}
Output:
enter the limit:
5
enter the elements:
54321
the created max heap
5 4 3 2 1
the sorted list:
1 2 3 4 5
Result: Thus, the heap sort is implemented