0% found this document useful (0 votes)
13 views98 pages

LateralEx6 To 14 Record 2

Computer science engineering oops lab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views98 pages

LateralEx6 To 14 Record 2

Computer science engineering oops lab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

1

University V.O.C. College of


Engineering

THOOTHUKUDI – 628 008


2024
NAME
DEGREE: B.E
BRANCH/SEMESTER: EEE / III SEM
REGISTER NO.

Certificate
This is a bonafide record-2 of Practical work done by the above mentioned
candidate in CS3362/ C PROGRAMMING and DATA STRUCTURES

LABORATORY at University V.O.C. College of Engineering, Thoothukudi

during the period Aug 2024 - December 2024


STATION: THOOTHUKUDI-8.
DATE:

Faculty-in-Charge Head of the Department

Submitted for the Anna University Practical Examination held at


University V.O.C. College of Engineering, Thoothukudi on
……………………………….....

Internal Examiner External Examiner


2

CS3362 C PROGRAMMING AND DATA STRUCTURES LABORATORY


LTPC
0 0 3 1.5

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:

At the end of the course the students will be able to:

CO1 Use Different Constructs of C and develop applications


CO2 Write functions to implement linear and non-linear data structure operations
CO3 Suggest and use the appropriate the linear / non-linear data structure operations
for a givenproblem
CO4 Apply appropriate hash functions that result in a collision free scenario for
data storageand
Retrieval
CO5 Implement sorting and searching algorithms for a given application
3

INDEX PAGE

Sl. Date Name of the Page


No Experiment No
6 Array 6
Implementation of
List ADT

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

11 Binary Search Tree 66


Implementation
12a Linear Search 74
12b Binary Search 75
13a Insertion Sort 77
13b Quick Sort 79
13c Merge Sort 81
14a Hash Table - Linear 83
Probing
14b Hash Table- 85
Quadratic Probing
14c Hash Table - Double 87
hashing
14d Hash table - 90
Separate Chaining
15 Construction of 92
Expression Tree,
Traversals
16 Heap Sort 96
5

Record -2
6

Ex.No:6 Array implementation of List ADT


Date:

Aim: To implement the list using arrays

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

The elements in the list


10 1.insert 2.delete 3.Makeempty 4.findelement
5.exit
enter your choice
1
enter the element to be inserted
5
enter the position
0
after insertion
10

The elements in the list


5 10 1.insert 2.delete 3.Makeempty 4.findelement
5.exit
enter your choice
1
enter the element to be inserted
13
enter the position
1
after insertion

The elements in the list


5 13 10 1.insert 2.delete 3.Makeempty
4.findelement 5.exit
enter your choice
2
enter the position of the element to be deleted
1
after deletion

The elements in the list


5 13 1.insert 2.delete 3.Makeempty 4.findelement
5.exit
enter your choice
4
enter the element to be searched
13
position of the element=1
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice
4
enter the element to be searched
80
element not found
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice
3
The elements in the list
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice
5

Result: Thus, singly linked list is implemented using arrays


11

Ex.No:7a Array Implementation of Stack


Date:

Aim: To implement stack using arrays

Algorithm:

Stack is a collection of elements in which insertion (push operation)


and deletion (pop operation) can be done only at the top

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

Result: Thus, the stack is implemented using arrays


15

Ex.No:7b Array implementation of Queue/ circular Queue


Date:

Aim: To write a program to implement circular queue using arrays

Algorithm:

1. front variable points to the position of first element in the queue


2. rear variable points to the position of last element in the queue
3. count holds the total number of elements in the queue

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 que[max];// queue is a collection of elements where deletion


//can be done at front end,
}; // insertion can be done in rear end
void initial(struct queue *q)
{
q->front=0;//when there are no elements, front=0, rear=-1 and
//count=0
q->rear=-1;
q->count=0;
}
void enqueue(struct queue *q, int e)//will perform insertion at rear end
{
if(q->count==max)// if count=max, max no. of elements are stored in
//queue,
{ // therefore queue is full, insertion cannot be done
printf("queue full\n");
goto xy;
}
q->rear=(q->rear+1)%max;// inc rear, take modulo div to avoid non
//existing
q->que[q->rear]=e; // position. Insert the element in rear
q->count++; // increment the total number of elements
xy: ;
}
int dequeue(struct queue *q)// will perform deletion at front end
{
int e;
if(q->count==0)// if count=0, no elements are in queue, therefore
//deletion
{ // is not possible
printf("queue is empty\n");
e=-1;
goto xy;
}
e=q->que[q->front];//store the element(to be deleted) in
//front position in e
q->front=(q->front+1)%max;// inc front, to remove 1st
//element,take modulo
q->count--;// value to avoid non existing position, dec total
//no. of elements
xy:return e;// return the deleted element
}
void display(struct queue *q)
{
17

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:

1.producer 2. consumer 3.exit


enter your choice
1
enter the element to be inserted
10
10
1.producer 2. consumer 3.exit
enter your choice
1
enter the element to be inserted
3
10 3
1.producer 2. consumer 3.exit
enter your choice
1
enter the element to be inserted
20
10 3 20
1.producer 2. consumer 3.exit
enter your choice
2
the deleted element=10
3 20
1.producer 2. consumer 3.exit
enter your choice
3

Result: Thus, the program to implement queue using circular array is


executedand the results are verified.
19

Ex.No:8a Linked List Implementation of List


Date:

Aim: To implement list using linked list

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:

//Linked List implementation of list ADT


#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>

struct listnode //node contains data(entry) and address of


{ // next node
int entry;
struct listnode *next;
};

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 initial(struct listlink *l) // will initialize head as NULL and


//count as 0
{
l->head=NULL;
l->count=0;
}

void insert(struct listlink *l,int p1,int e1)


{
int i;
struct listnode *ptr,*newnode,*adjacent;
if(p1<0||p1>l->count+1) // if position is <0 or position
//is>count+1 display
{ // “wrong position” and stop insertion
printf("wrong position\n");
goto xy;
}
newnode=(struct listnode*)malloc(sizeof(struct listnode));
// create a //newnode using
newnode->entry=e1; // malloc()(dynamic memory allocation
//– run time allocation)
newnode->next=NULL;// store element in data field(entry),
//NULL in next
if(p1==0) // if position ==0 , make the newly created node as
//head node
21

{
newnode->next=l->head;
l->head=newnode;
}

else // if position !=0


{
ptr=l->head; // store head in ptr
for(i=1;i<p1;i++) // move ptr to the previous position in
//which the insertion
ptr=ptr->next; // should be done
adjacent=ptr->next; // change the links to perform insertion
ptr->next=newnode;
newnode->next=adjacent;
}
l->count++; // increment the total number of nodes
xy:;
}

void delete1(struct listlink *l,int p1)


{
int i;
struct listnode *ptr,*adjacent;
if(p1<0||p1>=l->count) // if position <0 or position >=count
{ // display “wrong position” and stop deletion
printf("wrong position\n");
goto xy;
}
if(p1==0) // if position=0, delete the head node by changing the
//address
l->head=l->head->next; // stored in head node
else
{
ptr=l->head; // store head in ptr node
for(i=1;i<p1;i++) // move ptr to the previous position in
//which the deletion
ptr=ptr->next; // should be performed
adjacent=ptr->next;// change the links to perform deletion
ptr->next=adjacent->next;
}
l->count--; // decrement the total number of nodes
xy:;
}
void display(struct listlink *l)
{
int i;
22

struct listnode *ptr;


printf("\n The elements in the list");
ptr=l->head; // store head in ptr
for(i=0;i<l->count;i++)
{
printf("%d\t",ptr->entry); // print the data field(entry)
ptr=ptr->next; // move to next node
}
}

struct listnode* find(struct listlink *l,int e1)


{
struct listnode *ptr=l->head;// store head in ptr
int i;
for(i=0;i<l->count;i++)
if(ptr->entry==e1)// compare the data field with the
//element that we want
return ptr;// to search. If the is a match return address
else
ptr=ptr->next; // move to next node by changing ptr
return NULL; // when element not found return NULL
}

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

display(&l1);// will display elements of linked list


break;
case 2:
printf("enter position of element to be deleted\n");
scanf("%d",&p);
delete1(&l1,p);// will delete the node in position p
printf("after deletion\n");
display(&l1);
break;
case 3:
initial(&l1); // will make list empty by initializing it
printf("List after make empty\n");
display(&l1);
break;
case 4:
printf("enter the element to be searched\n");
scanf("%d",&e);
ptr=find(&l1,e); //call fn find- return address of node
if(ptr!=NULL)// if ptr!=NULL, print the address of
printf("position of the element=%ld\n",ptr);// node
else
printf("element not found\n"); //if ptr=NULL,
//display “element not found”
break;
case 5:
exit(1);// terminate the program

}
}
}

Output:

1.insert 2.delete 3.Makeempty 4.findelement 5.exit


enter your choice1
enter the element to be inserted
10
enter the position
0
The elements in the list10
1.insert 2.delete 3.Makeempty 4.findelement 5.exit
enter your choice1
enter the element to be inserted
24

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

Result: Thus, the program to implement list using linked list is


executed and theresults are verified.
25

Ex.No: 8b Linked List Implementation of stack


Date:

Aim: To write a program to implement stack using linked list

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

void initial(struct stack1 *s)//initial stack contains nothing, top=NULL


{
s->top=NULL;
}
void push(struct stack1 *s,int e1)
{
struct node *ptr;
ptr=(struct node*)malloc(sizeof(struct node));//create a new node
//using malloc function
if(ptr==NULL)//if malloc not able to allocate memory display
//error message
{
printf("node cannot be created\n");
goto xy;
}
ptr->entry=e1;//insert the element e1 in the data field of the node
ptr->next=s->top;//connect the newly created node with top
s->top=ptr;// make the newly created node as top xy: ;
}
int pop(struct stack1 *s)
{
int e1;
if(s->top==NULL)//if top==NULL, stack contains no elements
{
printf("stack empty\n");
e1=-1;
goto xy;
}
e1=s->top->entry;//store the data field of top in e1
s->top=s->top->next;//move top to next node, so that current top
//will be removed from the stack
xy: return e1;//return the data field of deleted node
}
void display(struct stack1 *s)
{ struct node *ptr;
ptr=s->top;
printf("the elements of the stack\n");
for(;ptr!=NULL;ptr=ptr->next)//move ptr from top to NULL and
//print data field
printf("%d\t",ptr->entry);
}
void main()
{ struct stack1 s1;
int e,choice;
initial(&s1);// will call the function initial to initialize top to
//NULL
clrscr();
27

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

Ex.No:8c Linked List Implementation of Queue


Date:

Aim: To write a program to implement queue using linked list

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:

//linked list implementation of queue


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
#define max 10

struct node// node contains data field(entry) and address of next


//node(*next)
{
int entry;
struct node *next;
};
29

struct queue // queue contains two pointers


{
struct node *front;//pointer front holds the address of first node
struct node *rear;//pointer rear holds the address of last node
int count;//count will have the total number of elements in the
//queue
};

void initial(struct queue *q)//will initialize the data members of the


//queue
{
q->front=NULL;//when there are no elements pointer front points
//to NULL,
q->rear=NULL;// pointer rear points to NULL
q->count=0;// count will have a value of zero
}

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 display(struct queue *q)


{
int i;
struct node *ptr=q->front;
printf("elements in queue\n");
for(i=0;i<q->count;i++)
{
printf("%d\t",ptr->entry);// print the data field of all the
//nodes by moving ptr from
ptr=ptr->next; // front to last node
}
}

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

printf("enter the element to be inserted\n");


scanf("%d",&e1);
enqueue(&q1,e1);// will call fn enqueue, insert
//element e1in queue
display(&q1);
break;
case 2:
e1=dequeue(&q1);// will call fn dequeue, delete front
//node of queue
printf("the deleted element=%d\n",e1);
display(&q1);
break;
case 3:
exit(1);// terminate the program
} } }
Output:
1.producer 2. consumer 3.exit
enter your choice
1
enter the element to be inserted
10
10
1.producer 2. consumer 3.exit
enter your choice
1
enter the element to be inserted
3
10 3
1.producer 2. consumer 3.exit
enter your choice
1
enter the element to be inserted
20
10 3 20
1.producer 2. consumer 3.exit
enter your choice
2
the deleted element=10
3 20
1.producer 2. consumer 3.exit
enter your choice
3
Result: Thus, the program to implement queue using linked list is
executed andthe results are verified
32

Ex.No:9a Applications of List- Polynomial Addition


Date:

Aim: To implement polynomial addition using singly linked list

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 listnode //node contains coefficient, exponent and address


//of next node
{
int coeff;
int expo;
struct listnode *next;
};
33

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 initial(struct listlink *l)//will initialize head as NULL and count as 0


{
l->head=NULL;
l->count=0;
}

void insert(struct listlink *l,int p1,int e1) //p1 represents exponent, e1


/ /represents coefficient
{
int i;
struct listnode *ptr,*newnode,*adjacent;
if(p1<0||p1>l->count+1) // if position is <0 or position
//is>count+1 display
{ // “wrong position” and stop insertion
printf("wrong position\n");
goto xy;
}
newnode=(struct listnode*)malloc(sizeof(struct listnode));
// create a new node using
newnode->coeff=e1; // malloc() dynamic memory allocation
//– run time
newnode->expo=p1;
newnode->next=NULL;// store element in data field(entry),
//NULL in next
if(p1==0) // if position ==0, make the newly created node as
//head node
{
newnode->next=l->head;
l->head=newnode;
}
else // if position !=0
{
ptr=l->head; // store head in ptr
for(i=1;i<p1;i++) // move ptr to the previous position in
//which the insertion
ptr=ptr->next; // should be done
adjacent=ptr->next; // change the links to perform
//insertion
ptr->next=newnode;
newnode->next=adjacent;
}
34

l->count++; // increment the total number of nodes xy:;


}

void display(struct listlink *l)


{
int i;
struct listnode *ptr;
printf("\n The elements in the list");
ptr=l->head; // store head in ptr
for(i=0;i<l->count;i++)
{
printf("%dx%d\t",ptr->coeff,ptr->expo); // print the data field(entry)
ptr=ptr->next; // move to next node
}
}

void add(struct listlink *d1,struct listlink *d2,struct listlink *d3)


{
struct listnode *ptr1,*ptr2;
int c,i;
ptr1=d1->head; // store head in ptr
ptr2=d2->head;
for(i=0;i<d1->count;i++)
{
insert(d3,ptr1->expo,ptr1->coeff+ptr2->coeff);//create the
//resultant polynomial by
ptr1=ptr1->next;//adding two polynomials and insert them
//into resultant polynomial
ptr2=ptr2->next; // move to next node
}
printf(“After Addition\n”);
display(d3);
}

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

printf("enter the first polynomial\n");


while(1)
{
printf("1.insert\t2.exit\n");
printf("enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter the coefficient to be inserted\n");
scanf("%d",&e);
printf("enter the exponent\n");
scanf("%d",&p);
insert(&l1,p,e); // will insert the node with
//element e in position p
printf("after insertion\n");
display(&l1); // will display the elements
//of linked list
break;
case 2:
goto l2;
}}
l2: printf("enter the second polynomial\n");
while(1)
{
printf("1.insert\t2.exit\n");
printf("enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter the coefficient to be inserted\n");
scanf("%d",&e);
printf("enter the exponent\n");
scanf("%d",&p);
insert(&l2,p,e); // will insert the node with
//element e in position p
printf("after insertion\n");
display(&l2);
// will display the elements of linked list
break;
case 2:
goto l3;
}}
l3:add(&l1,&l2,&l3);
}
36

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
11
enter the exponent
1
after insertion

The elements in the list10x0 11x1


1.insert 2.exit
enter your choice2
enter the second polynomial
1.insert 2.exit
enter your choice1
enter the coefficient to be inserted
20
enter the exponent
0
after insertion
The elements in the list20x0
1.insert 2.exit
enter your choice1
enter the coefficient to be inserted
9
enter the exponent
1
after insertion
The elements in the list20x0 9x1
1.insert 2.exit
enter your choice2
After Addition
The elements in the list30x0 20x1

Result: Thus, the program to add two polynomials using singly linked
list isexecuted and the results are verified.
37

Ex.No:9b Applications of Stack-Balancing parenthesis


Date:

Aim: To write a program to check whether the infix expression is


having properopening and closing parenthesis or not.

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

struct stack1 // stack contains the address of top node


{
struct node *top;
};

void initial(struct stack1 *s)// initially stack contains nothing, therefore


//top=NULL
{
s->top=NULL;
}
38

void push(struct stack1 *s,char e1)


{
struct node *ptr;
ptr=(struct node*)malloc(sizeof(struct node));//create a new node
//using malloc function
if(ptr==NULL)//if malloc unable to allocate memory display error
{
printf("node cannot be created\n");
goto xy;
}
ptr->entry=e1;//insert the element e1 in the data field of the node
ptr->next=s->top;//connect the newly created node with top
s->top=ptr;// make the newly created node as top
xy: ;
}

char pop(struct stack1 *s)


{
char e1;
if(s->top==NULL)//if top==NULL, stack contains no elements
{
printf("stack empty\n");
e1=-1;
goto xy;
}
e1=s->top->entry;//store the data field of top in e1
s->top=s->top->next;//move top to next node, so that current top
//will be removed from the stack
xy: return e1;//return the data field of deleted node
}

void display(struct stack1 *s)


{
struct node *ptr;
ptr=s->top;
printf("the elements of the stack\n");
for(;ptr!=NULL;ptr=ptr->next)//move ptr from top to NULL and
//print data field
printf("%c\t",ptr->entry);
}
39

.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

Ex.No:9c. Applications of queue –Storing elements according to


age -Linked list implementation of Queue
Date:

Aim: To write a program to implement priority queue using linked list

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

Program: //linked list implementation of priority queue


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
struct node// node contains data field (name, age) and address of next
//node(*next)
{ char name[30];
int age;
struct node *next;
};
struct queue // queue contains two pointers
{ struct node *front;//pointer front holds the address of first node
struct node *rear;//pointer rear holds the address of last node
int count;//count will have the total number of elements in the
//queue
};
41

void initial(struct queue *q)//will initialize the data members of the


//queue
{ q->front=NULL;//when there are no elements front points to NULL
q->rear=NULL;// pointer rear points to NULL
q->count=0;// count will have a value of zero
}

void enqueue(struct queue *q,char *n,int a)//will insert the element(n,a)


//inside the queue
{ struct node *ptr,*t,*prev;
ptr=(struct node*)malloc(sizeof(struct node));//create a node
if(ptr==NULL)// if the node is not created ptr will be equivalent to NULL
{
printf("node cannot be created\n");// print “ node cannot be
//created”
goto xy;//stop inserting
}
strcpy(ptr->name,n);//after node is created, place n,a in data field
//of node ptr
ptr->age=a;
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
t=q->front;
while(a>t->age)//compare age of newly created node with
{ //other nodes and insert the new node in its place
prev=t;
t=t->next;
}
if(t==NULL)
{
prev->next=ptr;
q->rear=ptr;
}
if(q->front==q->rear)
if(ptr->age<q->front->age)
42

{
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 display(struct queue *q)


{ int i;
struct node *ptr=q->front;
printf("elements in queue\n");
for(i=0;i<q->count;i++)
{
printf("%s\t%d\n",ptr->name,ptr->age);// print the data
//field(name,age) of all the nodes by moving ptr from
ptr=ptr->next; // front to last node
}
}
43

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

Ex.No:9d Applications of List- Polynomial multiplication


Date:

Aim: To implement polynomial multiplication using singly linked list

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)

void initial(struct listlink *l)//will initialize head as NULL and count as 0


{
l->head=NULL;
l->count=0;
}

void insert(struct listlink *l,int p1,int e1) //p1 represents exponent, e1


//represents coefficient
{
int i;
struct listnode *ptr,*newnode,*adjacent;
if(p1<0||p1>l->count+1) // if position is <0 or position is >
//count+1 display “wrong position”, stop insertion
printf("wrong position\n");
goto xy;
}
newnode=(struct listnode*)malloc(sizeof(struct listnode));
// create newnode
newnode->coeff=e1;// malloc()(dynamic memory allocation – run time
newnode->expo=p1;
newnode->next=NULL;//store element in data field(entry), NULL in next
if(p1==0)// if position ==0, make the newly created node as head node
{
newnode->next=l->head;
l->head=newnode;
}
else // if position !=0
{
ptr=l->head; // store head in ptr
for(i=1;i<p1;i++) //move ptr to the previous position in which the
ptr=ptr->next;// insertion should be done
adjacent=ptr->next;// change the links to perform insertion
ptr->next=newnode;
newnode->next=adjacent;
46

}
l->count++; // increment the total number of nodes
xy:;
}

void display(struct listlink *l)


{
int i;
struct listnode *ptr;
printf("\n The elements in the list");
ptr=l->head; // store head in ptr
for(i=0;i<l->count;i++)
{
printf("%dx%d\t",ptr->coeff,ptr->expo); //print coeff, expo
ptr=ptr->next; // move to next node
}
}

void mul(struct listlink *d1,struct listlink *d2,struct listlink *d3)


{
struct listnode *ptr1,*ptr2;
int c,i,j;
ptr1=d1->head;// store head in ptr
//ptr2=d2->head;
for(i=0;i<d1->count;i++)
{
ptr2=d2->head;
for(j=0;j<d2->count;j++)
{
insert(d3,ptr1->expo+ptr2->expo,ptr1->coeff*ptr2-
>coeff);//result polynomial
ptr2=ptr2->next; // move to next node
}
ptr1=ptr1->next;
}
printf(“After Multiplication\n”);
display(d3);
}

void main()
{
struct listnode *ptr;
struct listlink l1,l2,l3;
int choice,e,p;
clrscr();
47

initial(&l1);// will initialize linked list l1


initial(&l2);
initial(&l3);
printf("enter the first polynomial\n");
while(1)
{
printf("1.insert\t2.exit\n");
printf("enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter the coefficient to be inserted\n");
scanf("%d",&e);
printf("enter the exponent\n");
scanf("%d",&p);
insert(&l1,p,e);// will insert the node with
//element e in position p
printf("after insertion\n");
display(&l1);// will display the elements of
//linked list
break;
case 2:
goto l2;
}
}
l2: printf("enter the second polynomial\n");
while(1)
{ printf("1.insert\t2.exit\n");
printf("enter your choice");
scanf("%d",&choice);
switch(choice)
{ case 1:
printf("enter the coefficient to be inserted\n");
scanf("%d",&e);
printf("enter the exponent\n");
scanf("%d",&p);
insert(&l2,p,e); // will insert the node with
//element e in position p
printf("after insertion\n");
display(&l2);// will display the elements of
//linked list
break;
case 2:
goto l3;
}
48

}
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

The elements in the list10x0 5x1


1.insert 2.exit
enter your choice2
enter the second polynomial
1.insert 2.exit
enter your choice1
enter the coefficient to be inserted
20
enter the exponent
0
after insertion
The elements in the list20x0
1.insert 2.exit
enter your choice1
enter the coefficient to be inserted
6
enter the exponent
1
after insertion
The elements in the list20x0 6x1
1.insert 2.exit
enter your choice2
After Multiplication
The elements in the list200x0 100x1 30x2 60x1
Result: Thus, the program to multiply two polynomials using singly
linked list isexecuted and the results are verified.
49

Ex.No:9e Conversion of Infix to Postfix Expression


Date:

Aim: To convert infix to postfix expression

Algorithm:

1. Push $ into the stack


2. Read infix expression
3. For each character
a. If it is operand, add it to postfix expression
b. If it is not operand
i. If), pop the element from the stack and add it to postfix
expression till (. Do not add (
ii.If not )
while inputpriority(infix character ) <=
stackpriority (stacktop entry)
pop and add it topostfix expression
Push the element
4. Pop all the elements from stack and add it to postfix expression
till $

Input priority: ( --- 3,------ * ------- 2, / ---- 2, + ----- 1, 1


Stack priority: ( ---- 0, --- * ------ 2, / ---- 2, + ----- 1, - ---- 1, $ 1

Program:

Header file – stack1.h

//linked list implementation of stack


#include<stdio.h>
#include<process.h>

struct node //node contains data field(entry) and address of next node
{
char entry;
struct node *next;
};

struct stack1 // stack contains the address of top node


{
struct node *top;
};
50

void initial(struct stack1 *s)// initially stack contains nothing, therefore


//top=NULL
{
s->top=NULL;
}
void push(struct stack1 *s,char e1)
{
struct node *ptr; //create a new node using malloc function
ptr=(struct node*)malloc(sizeof(struct node));
if(ptr==NULL)//if malloc not able to allocate memory display
//error message
{
printf("node cannot be created\n");
goto xy;
}
ptr->entry=e1;//insert the element e1 in the data field of the node
ptr->next=s->top;//connect the newly created node with top
s->top=ptr;// make the newly created node as top
xy: ;
}

char pop(struct stack1 *s)


{
char e1;
if(s->top==NULL)//if top==NULL, stack contains no elements
{
printf("stack empty\n");
e1=-1;
goto xy;
}
e1=s->top->entry;//store the data field of top in e1
s->top=s->top->next;//move top to next node, top will be removed
//from the stack
xy: return e1;//return the data field of deleted node
}

void display(struct stack1 *s)


{
struct node *ptr;
ptr=s->top;
printf("the elements of the stack\n");
51

for(;ptr!=NULL;ptr=ptr->next)//move ptr from top-NULL,


//print data field
printf("%c\n",ptr->entry);
}

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

int isoperand(char c)// will return true if character is operand ,


//otherwise false
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c==')'||c=='(')
return 0;
else
return 1;
}

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*

Result: Thus, the infix expression is converted into postfix expression


54

Ex.No:9f Evaluation of Postfix expression


Date:

Aim: To write a program to evaluate postfix expression

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

//Header file – stack2.h


//linked list implementation of stack
#include<stdio.h>
#include<process.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;
};

void initial(struct stack1 *s)// initial stack contains nothing,


//top=NULL
{
s->top=NULL;
}

void push(struct stack1 *s,int e1)


{
struct node *ptr;
55

//create a new node using malloc function


ptr=(struct node*)malloc(sizeof(struct node));
if(ptr==NULL)//if malloc not able to allocate memory display error
//message
{
printf("node cannot be created\n");
goto xy;
}
ptr->entry=e1;//insert the element e1 in the data field of the node
ptr->next=s->top;//connect the newly created node with top
s->top=ptr;// make the newly created node as top
xy: ;
}

int pop(struct stack1 *s)


{
int e1;
if(s->top==NULL)//if top==NULL, stack contains no elements
{
printf("stack empty\n");
e1=-1;
goto xy;
}
e1=s->top->entry;//store the data field of top in e1
s->top=s->top->next;//move top to next node, current top-
//removed from the stack
xy: return e1;//return the data field of deleted node
}

void display(struct stack1 *s)


{
struct node *ptr;
ptr=s->top;
printf("the elements of the stack\n");
for(;ptr!=NULL;ptr=ptr->next)
//move ptr from top-NULL,print datafield
printf("%d\n",ptr->entry);
}

C Program:

#include "stack1.h"
#include <ctype.h>
56

int isoperator(char c)// will return true if character is operator,


//otherwise false
{
if(c=='+'||c=='-'||c=='*'||c=='/')
return 1;
else
return 0;
}

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:

enter the postfix expression54+9*


value of postfix expression=81

Output2:
enter the postfix expression54+8-
value of postfix expression=1

Output3:
enter the postfix expression54*3+
value of postfix expression=23

Result: Thus, the program to evaluate the postfix expression is


executed and theresults are verified
58

Ex.No:9g Palindrome using Stack


Date:

Aim: To write a C program to check whether the given string is


palindrome ornot using stack

Algorithm:

1. Create the stack with push and pop operations


2. Enter the string
3. Push the characters of the string from first character to last character on
tothe stack
4. Pop the stack and store in in a 2nd string, so that sting2 will be reverse
of1st string
5. Compare string1, string2
6. If equal print “palindrome”
7. If not equal print “not palindrome”

Program:

Stack2.h

//Header file – stack1.h


//linked list implementation of stack
#include<stdio.h>
#include<process.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;
};

void initial(struct stack1 *s)// initial stack = nothing, top=NULL


{
s->top=NULL;
}
59

void push(struct stack1 *s,int e1)


{
struct node *ptr;
//create a new node using malloc function
ptr=(struct node*)malloc(sizeof(struct node));
if(ptr==NULL)//if malloc not able to allocate memory display
//error message
{
printf("node cannot be created\n");
goto xy;
}
ptr->entry=e1;//insert the element e1 in the data field of the node
ptr->next=s->top;//connect the newly created node with top
s->top=ptr;// make the newly created node as top xy: ;
}

int pop(struct stack1 *s)


{
int e1;
if(s->top==NULL)//if top==NULL, stack contains no elements
{
printf("stack empty\n");
e1=-1;
goto xy;
}
e1=s->top->entry;//store the data field of top in e1
s->top=s->top->next;//move top to next node, top will be
//removed
xy: return e1;//return the data field of deleted node
}

void display(struct stack1 *s)


{
struct node *ptr;
ptr=s->top;
printf("the elements of the stack\n");
for(;ptr!=NULL;ptr=ptr->next)//move ptr from top-NULL, print
//data field
printf("%d\n",ptr->entry);
}
60

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

Result: Thus, the C program to check whether the given string is


palindrome ornot using stack is executed and the result is verified.
61

Ex.No:9h Palindrome using Queue


Date:

Aim: To write a C program to find out whether the given string is


palindromeor not using queue

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

// queue contains two pointers

struct node *front;//pointer front holds the address of first node


struct node *rear;//pointer rear holds the address of last node
int count;//count will have the total number of elements in the queue

void initial();
void enqueue(int);
int dequeue();
void display();

void initial()//will initialize the data members of the queue


{
front=NULL;//when no elements pointer front points to NULL,
rear=NULL;// pointer rear points to NULL
count=0;// count will have a value of zero
}
62

void enqueue(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 created ptr will be NULL
{ // Therefore print " node cannot be created"
printf("node cannot be created\n");
goto xy;//stop inserting
}
ptr->entry=e;//after node is created, place e in data field of node
ptr->next=NULL;// store NULL in address field of ptr
count++;//increment the total number of nodes in the queue
if(front==NULL && rear==NULL)//if front, rear both=NULL,
{ // the newly create node is the first node
front=ptr;//therefore make newly created node as front, rear
rear=ptr;
}
else
{ // if the node is not first node connect already available rear to
//newly created node ptr
rear->next=ptr;
rear=ptr;// make the newly created node as rear
}
xy: ;
}

int dequeue()// will delete front node from the queue


{
int e;
//if no. of nodes = 0, no nodes are available, deletion not possible
if(count==0)
{
printf("queue is empty\n");
e=-1;
goto xy;
}
e=front->entry;//store the data field of the node to be deleted in e
// remove the node, by moving front to next available node
front=front->next;
if(front==NULL)//If front=NULL, all the node are deleted,
rear=NULL; // therefore make rear also to NULL
count--;//decrement the total number of nodes
63

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

Ex.No:10 Implementation of Binary Tree and its operations


Date:
Aim: To implement the binary tree and its operations
Algorithm:
1. Create node with data and pointers left, right
2. Write a function newNode to create a new node with data, null in left
andright
3. Write a function to perform in order traversal. (LVR)
4. Call the functions newNode and inorder in main function Program:
#include<stdio.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
/* newNode() allocates a new node with the given data and NULL left
and rightpointers. */
struct node* newNode(int data)
{ // Allocate memory for new node
struct node* node= (struct node*)malloc(sizeof(struct node));
// Assign data to this node
node->data = data; // Initialize left and right children as NULL
node->left = NULL;
node->right = NULL;
return (node);
}
void inorder(struct node *ptr)// LVR
{ if(ptr->left!=NULL)
inorder(ptr->left);
printf("%d\t",ptr->data);
if(ptr->right!=NULL)
inorder(ptr->right);
}
int main()
{ struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
inorder(root);
return 0;
}
Output:
4 2 1 3
Result: Thus, the program to implement binary tree is executed and
the result isverified.
66

Ex.No:11 Binary Search Tree Implementation


Date:

Aim: To write a program implement binary search tree

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

4. Insert the element in the empty place found

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

struct node* find(struct node* ptr1,int e1)


//if ptr==NULL, element not found, return NULL
{
if(ptr1==NULL)
return NULL;
if(e1<ptr1->entry)// if el < data of ptr, search in left sub tree
return find(ptr1->left,e1);
else if(e1>ptr1->entry)// if el > data field of ptr, move to right sub
//tree search
return find(ptr1->right,e1);
else
return ptr1;// element found, return its address
}

struct node * findmin(struct node* ptr1)


{
if(ptr1==NULL)// if ptr==NULL, no nodes at all
return NULL;
else if(ptr1->left==NULL)// if no more nodes in left, it is smallest
//node, return its address
return ptr1;
else
return findmin(ptr1->left);// traverse towards left for leftmost
//node which is the smallest one
}

struct node* findmax(struct node *ptr1)


{
while(ptr1->right!=NULL)// traverse towards right till last node
ptr1=ptr1->right;
return ptr1;// return the address of right most node-largest element
}
void insert(struct node *ptr1,int e1)
{
if(ptr1==NULL)// if root==NULL, create a new node, make it as root
{
ptr1=(struct node*)malloc(sizeof(struct node));
ptr1->entry=e1;
ptr1->left=NULL;
ptr1->right=NULL;
if(t.count==0)
t.root=ptr1;
}
else if(e1<ptr1->entry && ptr1->left!=NULL)//if e1 < data field of ptr
insert(ptr1->left,e1);//travel towards left, proceed insertion
else if(e1>ptr1->entry && ptr1->right!=NULL)// if e1 > datafield of
71

insert(ptr1->right,e1);//ptr travel towards right, proceed insertion


else if(e1<ptr1->entry)// if empty position found in left sub tree,
//insert in left
{
ptr1->left=(struct node*)malloc(sizeof(struct node));
ptr1->left->entry=e1;
ptr1->left->left=NULL;
ptr1->left->right=NULL;
}
else if(e1>ptr1->entry)// if empty position found - right sub tree,
//insert right
{
ptr1->right=(struct node*)malloc(sizeof(struct node));
ptr1->right->entry=e1;
ptr1->right->left=NULL;
ptr1->right->right=NULL;
}
else
;
}
void remove1(struct node *ptr1,int e1)
{
//e1 is in left entry of ptr1, ptr1->left has no child
if(e1==ptr1->left->entry && ptr1->left->left==NULL && ptr1->left-
>right==NULL)
ptr1->left=NULL;
//e1 is in right of ptr1, ptr1->right has no child
else if(e1==ptr1->right->entry && ptr1->right->left==NULL && ptr1-
>right->right==NULL)
ptr1->right=NULL;
//e1 is in root, root is the only node
else if(t.count==1 && e1==ptr1->entry && ptr1->left==NULL &&
ptr1- >right==NULL)
t.root=NULL;
//e1 is in left entry of ptr1,ptr1->left has only one child ,that is in left side
else if(e1==ptr1->left->entry && ptr1->left->left!=NULL && ptr1->left-
>right==NULL)
ptr1->left=ptr1->left->left;
//e1 is in left of ptr1,ptr1->left has only one child, that is in right side
else if(e1==ptr1->left->entry && ptr1->left->left==NULL && ptr1-
>left->right!=NULL)
ptr1->left=ptr1->left->right;
//e1 is in right of ptr1, ptr1->right has only one child, that is in left side
else if(e1==ptr1->right->entry && ptr1->right->left!=NULL && ptr1-
>right->right==NULL)
ptr1->right=ptr1->right->left;
//e1 is in right of ptr1,ptr1->right has only one child, that is in right side
72

else if(e1==ptr1->right->entry && ptr1->right->left==NULL && ptr1-


>right->right!=NULL)
ptr1->right=ptr1->right->right;
//e1<entry of ptr1 search in left side- recursive delete
else if(e1<ptr1->entry)
remove1(ptr1->left,e1);
//e1>entry of ptr1, search in right side- recursive delete
else if(e1>ptr1->entry)
remove1(ptr1->right,e1);
//e1=entry of ptr1, ptr1 has two children
else if(e1==ptr1->entry && ptr1->left!=NULL&& ptr1>right!=NULL)
{
//find minimu in right, and replace current node
ptr1->entry=findmin(ptr1->right)->entry;
prev=ptr1;
//remove duplicate entry, by recursive deletion
remove1(ptr1->right,ptr1->entry);
}
//e1=entry of ptr1, ptr1 has only one child, that is in its left
else if(e1==ptr1->entry && ptr1->left!=NULL && ptr1>right==NULL)
ptr1=ptr1->left;
//e1=entry of ptr1, ptr1 has only one child, that is in its right
else if(e1==ptr1->entry && ptr1->left==NULL && ptr1>right!=NULL)
ptr1=ptr1->right;
//e1=entry pf ptr1, ptr1 has no children
else if(e1==ptr1->entry&&ptr1->left==NULL&&ptr1 >right==NULL)
{
prev->right=NULL;
ptr1=NULL;
}
}
void inorder(struct node *ptr)// LVR
{
if(ptr->left!=NULL)
inorder(ptr->left);
printf("%d\t",ptr->entry);
if(ptr->right!=NULL)
inorder(ptr->right);
}
void preorder(struct node *ptr) // VLR
{
printf("%d\t",ptr->entry);
if(ptr->left!=NULL)
preorder(ptr->left);
if(ptr->right!=NULL)
preorder(ptr->right);
}
73

void postorder(struct node *ptr) //LRV


{
if(ptr->left!=NULL)
postorder(ptr->left);
if(ptr->right!=NULL)
postorder(ptr->right);
printf("%d\t",ptr->entry);
}

Output:

Result: Thus, the program to implement binary search tree is executed


and theresults are verified
74

Ex.no:12a Linear Search


Date:

Aim: To write a C program to implement linear search.

Algorithm:

1. Declare n, a[20], pos, i,e


2. Read n
3. Read array a and element e to be searched
4. Assign pos=-1
5. Repeat for 1=1 ; i<n;i++
a. check a[i]=e then assign pos=i
6. Display pos

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

Output1: enter n Output2: enter n


7 5
enter n elements enter n elements
1 90 67 54 69 10 2 30 4 1
23 21
enter the element to enter the element to
be searched be searched
67 35
position of element element not found
67=2
Result: Thus, the C program to implement linear search is executed and
theresult is verified.
75

Ex.No:12b Binary Search


Date:

Aim: To write a C program to find an element in an array using binary


search

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

Result: Thus, the program to find an element in an array using binary


search isexecuted and the result is verified.
77

Ex.No:13a Insertion Sort


Date:

Aim: To write a program to arrange a set of elements in ascending and


descending order using Insertion sort.

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

Result: Thus, the program is executed, result is verified.


79

Ex.No:13b Quick Sort


Date:

Aim: To implement quick sort

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

printf("enter the total number of elements\n");


scanf("%d",&n);

printf("enter the elements\n");


for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick(a,0,n-1);
printf("the sorted list\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void quick(int a[],int first,int last)
{
if(first<last)
{
pivot=a[first];
i=first;
j=last;
80

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

Ex.No:13c Merge Sort


Date:

Aim: To write a program to implement Merge Sort

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];
}

void sort(int low, int high)


{
int mid;
if(low < high)
{
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
}
else
{
return;
}
}
void main()
{
int i;
clrscr();
printf("\nList before sorting\n");
for(i = 0; i < max; i++)
printf("%d ", a[i]);
sort(0, max-1);
printf("\nList after sorting\n");
for(i = 0; i < max; i++)
printf("%d ", a[i]);
}

Output:

List before sorting


10 4 9 26 2 31 3 5 42 44
List after sorting
2 3 4 5 9 10 26 31 42 44

Result: Thus, the program to implement Merge Sort is executed and the
result isverified.
83

Ex.No:14a Hash Table - Linear Probing


Date:

Aim: To write a program to implement a hash table.

Algorithm:

1. Hash function will return a value using which the element


can be storedin 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 called as mapping.
2. A simplest hash function will consider (element mod total
number ofelements) as location of the element inside the hash table.
3. Open addressing is a technique to implement hash tables
withoutlinked using linked list. There are 3 types in open addressing.
They are
a. Linear probing
b. Quadratic probing
c. Double hashing
4. Linear probing is a method of defining hash function to
calculate hashvalue. If the position pointed by hash value is not empty
in the hash table, the function will move to the next position in the table
to avoid collision.

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]);
}

int hashfn(int e1)


{
int ht;
ht=e1%10;
while(h[ht]!=0)
if(ht==9)
ht=0;
else
ht++;
return ht;
}

Output:

enter the total number of elements 5


enter 5 elements other than zero 99 2 56 78 9
the elements in hash table
9 0 2 0 0 0 56 0 78 99

Result: Thus, the hash table is implemented and the result is verified
85

Ex.No:14b Hash Table- Quadratic Probing


Date:

Aim: To write a program to implement quadratic probing

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

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 c=2,inc=1;
int ht,ht1;
ht=e1%10;
if(h[ht]!=0)
{
ht1=ht;
ht1++;
ht1=ht1%10;
if(h[ht1]==0)
return ht1;
}
while(h[ht]!=0)
{
inc=pow(c,2);
ht=ht+inc;
ht=ht%10;
c++;
}
return ht;
}
Output:
enter the total number of elements 5
enter 5 elements other than zero 1 11 121 55 99
the elements in hash table
0 1 11 0 0 121 55 0 0 99

Result: Thus, the program to implement quadratic probing is


executed, result is verified.
87

Ex.No:14c Hash Table - Double hashing


Date:

Aim: To write a program to implement double hashing

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:

1. Initialize the hash table as zero (represents no element)


2. Enter the elements
3. Apply the first hash function, calculate the hash value
If the position is not empty, apply the second hash function
hash2(X)=R-(X mod R), the resultant value can be added with the
previously found collided value, new position can be calculated
4. Place the element
5. Display the table after placing all the elements
88

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:

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

Result: Thus, the program to implement double hashing is executed,


result is verified.
90

Ex.No:14d Hash table - Separate Chaining


Date:

Aim: To write a program to implement separate chaining

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:

1. The linked list is implemented using arrays


2. A two-dimensional array is declared, first index will represent the
position, second index will represent the linked list
3. Calculate the hash value using the function
4. Store the element in the position in the linked list

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

printf("enter %d positive elements \n",n);


for(i=0;i<n;i++)
{
int k=0;
scanf("%d",&e);
while(h[hashfn(e)][k]!=-1)
k++;
h[hashfn(e)][k]=e;
}
printf("the elements in hash table\n");
for(j=0;j<max;j++)
{
for(i=0;i<10;i++)
if(h[j][i]!=-1)
{
printf("position=%d\n",j);
printf("%d\t",h[j][i]);
}
printf("\n");
}
}
int hashfn(int e1)
{
int ht;
ht=e1%10;
return ht;
}

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

Result: Thus, the program to implement separate chaining is


executed, result is verified.
92

Ex.No:15 Construction of Expression Tree, Traversals


Date:
Aim: To write a program to construct expression tree, to traverse it is
executedand the results are verified.

Algorithm:

1. Enter a postfix expression


2. In the postfix expression
a. If the character is operand create a node and push it to the stack
b. If the character is operator pop 2 operands from the stack, from a tree
, push it to the stack
3. The final tree will be in the stack

In order traversal:
1. LVR
2. Move to left pointer until NULL
3. Display the entry
4. Move to right pointer until NULL

Pre order traversal:


1. VLR
2. Display the entry
3. Move to left pointer until NULL
4. Move to right pointer until NULL

Post order traversal:


1. LRV
2. Move to left pointer until NULL
3. Move to right pointer until NULL
4. Display the entry

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

struct node* make(char);


struct node* makenode(char,struct node*,struct node*);
struct stack1 s1;
char postfix[50];
int i;
struct node *ptr1,*ptr2,*ptr3;
clrscr();
printf("enter the postfix expression\n");
scanf("%s",postfix);
initial(&s1);
for(i=0;postfix[i]!=0;i++)
if(!isoperator(postfix[i])) // if the character is operand
{
ptr1=make(postfix[i]);// make a node
push(&s1,ptr1);// push the node in the stack
}
else // if the character is operator
{
ptr1=pop(&s1);// pop two operands
ptr2=pop(&s1);
ptr3=makenode(postfix[i],ptr2,ptr1);// form a tree
push(&s1,ptr3);// push the tree in the stack
}
ptr1=pop(&s1);//pop the result from the stack
printf("inorder traversal\n");
inorder(ptr1);
printf("\npreorder traversal\n");
preorder(ptr1);
printf("\npost order traversal\n");
postorder(ptr1);
}
int isoperator(char c)
{
if(c=='+' || c=='-' || c=='*' || c=='/')
return 1;
else
return 0;
}
struct node* makenode(char c,struct node *p1,struct node *p2)
{
struct node *newptr;
newptr=(struct node*)malloc(sizeof(struct node));
newptr->entry=c;
95

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*

Result: Thus the program to construct the expression tree , traversals


is executedand the results are verified
96

Ex.No:16 Heap Sort


Date:

Aim: To implement heap sort

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy