0% found this document useful (0 votes)
83 views109 pages

DS Lab Manual

Here are the steps to implement a stack using an array in C: 1. Define the maximum size of the stack (MAX) and an array to represent it (Stack[MAX]) 2. Define variables to keep track of the top element: - top: Will point to the topmost element in the stack - -1 initially since stack is empty 3. Define functions for stack operations: - push(item): Checks if stack is full, if not pushes item to top and increments top - pop(): Checks if stack is empty, if not pops top item and decrements top - peek(): Returns top item without removing it - isEmpty(): Returns 1 if top is -1,
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)
83 views109 pages

DS Lab Manual

Here are the steps to implement a stack using an array in C: 1. Define the maximum size of the stack (MAX) and an array to represent it (Stack[MAX]) 2. Define variables to keep track of the top element: - top: Will point to the topmost element in the stack - -1 initially since stack is empty 3. Define functions for stack operations: - push(item): Checks if stack is full, if not pushes item to top and increments top - pop(): Checks if stack is empty, if not pops top item and decrements top - peek(): Returns top item without removing it - isEmpty(): Returns 1 if top is -1,
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/ 109

JCT COLLEGE OF ENGINEERING AND TECHNOLOGY

Pichaniur|Coimbatore-105

ISO 9001:2008 CERTIFIED INSTITUTION

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

III SEMESTER - REGULATION 2017

CS8381–DATA STRUCTURES LABORATORY RECORD

NAME

REG.NO.

CLASS

SUBJECT
JCT COLLEGE OF ENGINEERING AND TECHNOLOGY
PICHANUR,COIMBATORE-641105.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

BONAFIDE CERTIFICATE

CERTIFIED THAT THIS IS THE BONAFIDE RECORD OF WORK DONE BY __ ___

REG.NO FOR THE__________________________ __

LABORATORY ON THIS INSITUTION, AS PRESCRIBED BY THE ANNA UNVERSITY, FOR THE

__YEAR/SEMESTER DURING THE ACADEMIC YEAR 20__- 20___.

STAFF- IN-CHARGE HEAD OF THE DEPARTMENT

SUBMITTED FOR THE ANNA UNVERSITY PRACTICAL EXAMINATION HELD ON

INTERNAL EXAMINER EXTERNAL EXAMINER


JCT COLLEGE OF ENGINEERING AND TECHNOLOGY
PICHANUR,COIMBATORE-641105.

INDEX

PAGE STAFF
S.NO DATE NAME OF EXPERIMENT MARK
NO SIGN
PAGE STAFF
S.NO DATE NAME OF EXPERIMENT MARK
NO SIGN
JCT COLLEGE OF ENGINEERING AND TECHNOLOGY
PICHANUR,COIMBATORE-641105.

VISION

To emerge as a Premier Institute for developing industry ready engineers with competency,
initiative and character to meet the challenges in global environment.

MISSION

• To impart state-of-the-art engineering and professional education through strong theoretical basics
and hands on training to students in their choice of field.
• To serve our students by teaching them leadership, entrepreneurship, teamwork, values, quality,
ethics and respect for others.
• To provide opportunities for long-term interaction with academia and industry.
• To create new knowledge through innovation and research.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


VISION
To produce the leaders in the field of Computer Science and Engineering, evolving as a Centre
of Excellence for Learning and Research.

MISSION
Computer Science and Engineering Department is committed,
• To develop globally competent engineers capable of providing secure and Out-of-the Box
computing and cutting-edge technology solutions.
• To provide state-of-art laboratories and quality learning environment.
• To educate students with ethical values and to serve society with innovative, intelligent products
and services.
JCT COLLEGE OF ENGINEERING AND TECHNOLOGY
PICHANUR,COIMBATORE-641105.

Programme Educational Objectives (PEO)

PEO1: Graduates shall exhibit their sound theoretical, practical skills and knowledge for successful
employments or higher studies or research or entrepreneurial assignments.
PEO2: Graduates shall have lifelong learning skills, professional ethics and good communication capabilities
along with leadership skills, so that they can succeed in their life.
PEO3: Graduates shall become leaders, innovators and entrepreneurs by devising software solutions for
social issues and problems, thus caring for the society.

Programme Outcomes (PO)

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.

2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health
and safety, and the cultural, societal, and environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modelling to complex engineering activities with an understanding of
the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.

Program specific outcomes (PSO)

PSO1: Have capabilities to successfully qualify in national level competitive examinations for higher studies
and employment.

PSO2: Have abilities to apply their knowledge in the domain of Design and Analysis of Algorithms,
Computer Networks, Artificial Intelligence, Information Security, Data Science, Data Structure, Grid and
Cloud Computing, Software Engineering, Machine Learning, Operating Systems.
JCT COLLEGE OF ENGINEERING AND TECHNOLOGY
PICHANUR,COIMBATORE-641105.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


CS8381 – DATA STRUCTURES LABORATORY

SYLLABUS

COURSE OBJECTIVES

To implement linear and non-linear data structures


To understand the different operations of search trees
To implement graph traversal algorithms
To get familiarized to sorting and searching algorithms

LIST OF EXPERIMENTS:

1. Array implementation of Stack and Queue ADTs


2. Array implementation of List ADT
3. Linked list implementation of Stack, Queue and List ADTs
4. Applications of List, Stack and Queue ADTs
5. Implementation of Binary Trees and operations of Binary Trees
6. Implementation of Binary Search Trees
7. Implementation of AVL Trees
8. Implementation of Heaps using Priority Queues.
9. Graph representation and Traversal algorithms
10. Applications of Graphs
11. Implementation of searching and sorting algorithms
12. Hashing – any two collision techniques
TOTAL: 60 PERIODS

COURSE OUTCOMES

Upon completion of the course, students will be able to:


Write functions to implement linear and non-linear data structure operations
Suggest appropriate linear / non-linear data structure operations for solving a given
problem
Appropriately use the linear / non-linear data structure operations for a given problem
Apply appropriate hash functions that result in a collision free scenario for data storage and
retrieval
JCT COLLEGE OF ENGINEERING AND TECHNOLOGY
PICHANUR,COIMBATORE-641105.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LIST OF EXPERIMENTS:
1. Array implementation of Stack and Queue ADTs

2. Array implementation of List ADT

3. Linked list implementation of Stack, Queue and List ADTs

4. Applications of List, Stack and Queue ADTs

5. Implementation of Binary Trees and operations of Binary Trees

6. Implementation of Binary Search Trees

7. Implementation of AVL Trees

8. Implementation of Heaps using Priority Queues.

9. Graph representation and Traversal algorithms

10. Applications of Graphs

11. Implementation of searching and sorting algorithms

12. Hashing – any two collision techniques


13. Implement multiple stack in a single array using c language (CBS 1)
14. Implement topological sort using arrays using c language (CBS 2)
15. Implement expression tree using stacks find its in-order, preorder &
post-order traversals using c language (CBS 2)
Ex. No:
IMPLEMENTATION OF STACK ADT
1a

Date:

Aim:
To write a C program to implement Stack ADT by using arrays

Algorithm:
1. Create a Stack [ ] with MAX size as your wish.
2. Write function for all the basic operations of stack - PUSH(), POP() and DISPLAY().
3. By using Switch case, select push() operation to insert element in the stack.
o Step 1: Check whether stack is FULL. (top == SIZE-1)
o Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not
possible!!!" and terminate the function.
o Step 3: If it is NOT FULL, then increment top value by one (top++) and set
stack[top] to value (stack[top] = value).
4. Similarly, By using Switch case, select pop() operation to delete element from the
stack.
o Step 1: Check whether stack is EMPTY. (top == -1)
o Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not
possible!!!" and terminate the function.
o Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top
value by one (top--).
5. Similarly, By using Switch case, select display() operation to display all element
from the stack.
o Step 1: Check whether stack is EMPTY. (top == -1)
o Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the
function.
o Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with
top. Display stack[i] value and decrement i value by one (i--).
o Step 3: Repeat above step until i value becomes '0'.
6. Close the program
PROGRAM:

#include<stdio.h>
#include<conio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");

printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");


do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}

void pop()

{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

}
OUTPUT :
Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY


--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12

Enter the Choice:1


Enter a value to be pushed:24
Enter the Choice:1Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98
24
12
Press Next Choice

Enter the Choice:2

The popped elements is 98


Enter the Choice:3

The elements in STACK

24
12
Press Next Choice
Enter the Choice:4

EXIT POINT

Result:
Thus the C program to implement Stack ADT by using array is executed
successfully and the output is verified.
Ex. No: 1b IMPLEMENTATION OF QUEUE ADT

Date:
Aim:
To write a C program to implement Queue ADT by using arrays

Algorithm:
1. Create a Queue[ ] with MAX size as your wish.
2. Write function for all the basic operations of stack - Enqueue(), Dequeue() and
Display().
3. By using Switch case, select Enqueue() operation to insert element in to the
rear/back end of the queue.
Check whether queue is FULL. (rear == SIZE-1)
If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!"
and terminate the function.
If it is NOT FULL, then increment rear value by one (rear++) and set
queue[rear] = value
4. Similarly, by using Switch case, select Dequeue() function is used to remove the
element from the front end of the queue.
Check whether queue is EMPTY. (front == rear)
If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not
possible!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then increment the front value by one (front
++). Then display queue[front] as deleted element. Then check whether
both front and rear are equal (front == rear), if it TRUE, then set both front
and rear to '-1' (front = rear = -1).
5. Similarly, by using Switch case, select display() operation to display all element
of the queue.
Step 1: Check whether queue is EMPTY. (front == rear)
Step 2: If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the
function.
Step 3: If it is NOT EMPTY, then define an integer variable 'i' and set 'i =
front+1'.
Step 3: Display 'queue[i]' value and increment 'i' value by one (i++). Repeat
the same until 'i' value is equal to rear (i <= rear)
6. Close the program
PROGRAM:

#include<stdio.h>
#include<conio.h>
#define n 5
void main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;

//clrscr();
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\n Queue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case 4:
exit(0);

default:
printf("Wrong Choice: please see the options");
}
}
}
getch();
}

OUTPUT:
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 10
1.Insert element to queue
2. Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 15
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 20

1.Insert element to queue


2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 30

1.Insert element to queue


2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 2
Element deleted from queue is : 10
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
15 20 30
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 4

Result:
Thus the C program to implement Stack ADT by using array is executed
successfully and the output is verified.
EX NO: 2 IMPLEMENTATION OF LIST ADT

DATE

Aim:
To write a C program to implement List ADT by using arrays

Algorithm:
1. Create an array[ ] with MAX size as your wish.
2. Write function for all the basic operations of list - create(), insert(), deletion(),
search(), display().
3. By using Switch case, select create() operation to create the list.
List Will be in the form: A1, A2, A3, .... An
First Element of the List: A1
Last Element of the List: An
ith Element of the List: Ai ,
Position of Element Ai : i , Position ranges from 0 to N
Size of the List: N
Empty List: If Size of the list is Zero (i.e N=0), it is Empty List.
Precedes and Succeeds: For any list except empty list, we say that Ai+1
follows (or succeeds) Ai (i<N) and that Ai-1 precedes Ai (i>1)
4. Similarly, by using Switch case, select insert() operation to insert element in the list.
Insert x at position p in list L
If p = END(L), insert x at the end
If L does not have position p, result is undefined
5. Similarly, by using Switch case, select delete() function is used to remove the
element from the list.
delete element at position p in L
undefined if p = END(L) or does not exist
6. Similarly, by using Switch case, select search() function is used to retrieve the
required element from the list if it is available.
returns element at position p on L
undefined if p does not exist or p = END(L)
7. Similarly, by using Switch case, select display() operation to display all element of
the list
print the elements of L in order of occurrence
8. Close the program
PROGRAM:

#include<stdio.h>
#include<conio.h>
#define MAX 10
void create();
void insert();
void deletion();

void search();
void display();
int a,b[20], n, p, e, f, i, pos;
void main()
{
//clrscr();
int ch;
char g='y';
do
{
printf("\n main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice");
scanf("%d", &ch);

switch(ch)
{
case 1:
create();
break;
case 2:
deletion();
break;

case 3:
search();
break;

case 4:
insert();
break;

case 5:
display();
break;

case 6:
exit();
break;

default:
printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:::");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}

void create()
{
printf("\n Enter the number of nodes");

scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]);
}

void deletion()
{
printf("\n Enter the position u want to delete::");
scanf("%d", &pos);
if(pos>=n)
{
printf("\n Invalid Location::");
}
else
{
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\n The Elements after deletion");
for(i=0;i<n;i++)
{
printf("\t%d", b[i]);
}
}

void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &e);

for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("Value is in the %d Position", i);
}
else
{
printf("Value %d is not in the list::", e);
continue;
}
}
}

void insert()
{

printf("\n Enter the position u need to insert::");


scanf("%d", &pos);

if(pos>=n)
{
printf("\n invalid Location::");
}
else
{
for(i=MAX-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\n Enter the element to insert::\n");
scanf("%d",&p);
b[pos]=p;
n++;
}
printf("\n The list after insertion::\n");

display();
}
void display()
{
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
{
printf("\n\n%d", b[i]);
}
}
OUTPUT:
Main Menu
1. Create
2. Delete
3. Search
4. Insert
5.Display
6.Exit
Enter your Choice: 3
Enter the number of
nodes 3 Enter the
element: 67 Enter the
element: 69 Enter the
element: 71
Do You Want to continue: y
Main Menu
1. Create
2. Delete
3. Search
4. Insert
5. Display
6.Exit
Enter your Choice: 4
Enter the position u need to insert: 2
Enter the element to insert:
56 The list after insertion:
The elements of the list ADT are:
67
69
56
71
Do You Want to continue: y
Main Menu
1.Create
2. Delete
3. Search
4. Insert
5.Displa
y
6.Exit
Enter your Choice: 2
Enter the position u want to delete: 2
The elements after deletion: 67 69 71
Do You Want to continue: y
Main Menu
1.Create
2. Delete
3. Search
4. Insert
5. .Display
6.Exit
Enter your Choice: 3
Enter the element to be searched:
69 Value is in 1 position
Do You Want to continue: y
Main Menu
1.Create
2. Delete
3. Search
4. Insert
5.Displa
y
6.Exit
Enter your Choice: 5
The elements of the list ADT are:
67
69
71
Do You Want to continue: N

Result:
Thus the C program to implement List ADT by using array is executed
successfully and the output is verified.
Ex. No. : 3a LINKED LIST IMPLEMENTATION OF STACK ADT

Date:

Aim:
To write a C program to implement Stack ADT by using linked list

Algorithm:
1. Include all the header files which are used in the program. And declare all the
user defined functions.
2. Define a 'Node' structure with two members data and next.
3. Define a Node pointer 'top' and set it to NULL.
4. Implement the main method by displaying Menu with list of operations and
make suitable function calls in the main method.
5. push(value) - Inserting an element into the Stack
Create a newNode with given value.
Check whether stack is Empty (top == NULL)
If it is Empty, then set newNode → next = NULL.
If it is Not Empty, then set newNode → next = top.
Finally, set top = newNode.
6. pop() - Deleting an Element from a Stack
1. Check whether stack is Empty (top == NULL).
2. If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!"
and terminate the function
3. If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
4. Then set 'top = top → next'.
5. Finally, delete 'temp' (free(temp)).
7. display() - Displaying stack of elements
1. Check whether stack is Empty (top == NULL).
2. If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
3. If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
4. Display 'temp → data --->' and move it to the next node. Repeat the same
until temp reaches to the first node in the stack (temp → next != NULL).
5. Finally! Display 'temp → data ---> NULL'.
PROGRAM:

#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*top = NULL;
void push(int);
void pop();
void display();
void main()

{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}

void push(int value)


{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}

void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;

}
printf("%d--->NULL",temp->data);
}
}

OUTPUT
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:1
Enter the value to be insert: 3
Insertion Success
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:1
Enter the value to be insert: 5
Insertion Success
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:2
Deleted Element: 5

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice:3
3-> NULL
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:4
...Program finished with exit code 0

Result:
Thus the C program to implement Stack ADT by using linked list is executed
successfully and the output is verified.
LINKED LIST IMPLEMENTATION OF QUEUE ADT
Ex. No. : 3b

Aim:
To write a C program to implement Queue ADT by using linked list

Algorithm:

1. Include all the header files which are used in the program. And declare all the
user defined functions.
2. Define a 'Node' structure with two members data and next.
3. Define two Node pointers 'front' and 'rear' and set both to NULL.
4. Implement the main method by displaying Menu of list of operations and
make suitable function calls in the main method to perform user selected
operation.
5. Enqueue(value) - Inserting an element into the queue
o Create a newNode with given value and set 'newNode → next' to NULL.
o Check whether queue is Empty (rear == NULL)
o If it is Empty then, set front = newNode and rear = newNode.
o If it is Not Empty then, set rear → next = newNode and rear = newNode.
6. Dequeue() - Deleting an Element from queue
o Check whether queue is Empty (front == NULL).
o If it is Empty, then display "Queue is Empty!!! Deletion is not
possible!!!" and terminate from the function
o If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
o Then set 'front = front → next' and delete 'temp' (free(temp)).
7. Display() - Displaying queue of elements
o Check whether queue is Empty (front == NULL).
o If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
o If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
o Display 'temp → data --->' and move it to the next node. Repeat the same
until 'temp' reaches to 'rear' (temp → next != NULL).
o Finally! Display 'temp → data ---> NULL'.
PROGRAM:

#include < stdio.h>


#include < conio.h>
#include < malloc.h>
#include < process.h>
#include < ctype.h>

struct linear_queue
{
int info;
struct linear_queue *next;
}*front,*rear,*newnode,*ptr;

void menu();
void display();
int underflow();
void enqueue(int);
void dequeue();

void main()
{
clrscr();
menu();
}

void menu()
{
int choice,item;
printf("MENU");
printf("\n1. Insert into the queue");
printf("\n2. Delete from queue");
printf("\n3. Display");
printf("\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
clrscr();
printf("\nEnter the item tobe inserted: ");
scanf("%d",&item);
enqueue(item);
clrscr();
printf("\nAfter inserting queue is:\n");
display();
getch();
clrscr();
menu();
break;
case 2:
clrscr();
if(underflow()==1)
{
dequeue();
if(underflow()==1)
{
printf("\nAfter deletion queue is:\n");
display();
}
}
getch();
clrscr();
menu();
break;
case 3:
clrscr();

if(underflow()==1)
{
printf("The queue is:\n");
display();
}
getch();
clrscr();
menu();
break;
case 4:
exit(1);
default:
clrscr();
printf("Your choice is wrong\n\n");
menu();
}
}

int underflow()
{
if((front==NULL)&&(rear==NULL))
{
printf("\nQueue is empty");
return(0);
}
else
{
return(1);
}
}
void enqueue(int item)
{
newnode=(struct linear_queue*)malloc(sizeof(struct linear_queue));
newnode->info=item;
if((front==NULL)&&(rear==NULL))
{
front=newnode;
rear=newnode;
newnode->next=NULL;
}
else
{
rear->next=newnode;
newnode->next=NULL;
rear=newnode;
}
}

void dequeue()
{
if(front==rear)
{

front=NULL;
rear=NULL;
}
else
{
front=front->next;
}
}

void display()
{
int i;
ptr=front;
i=1;
while(ptr!=NULL)
{
printf("\nNode %d : %d",i,ptr->info);
ptr=ptr->next;
i++;
}
}
OUTPUT

:: Queue Implementation using Linked List:

****** MENU ******


1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 5
Insertion is Success!!!

****** MENU ******


1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 7

Insertion is Success!!!

****** MENU ******


1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 2

Deleted element : 5
****** MENU ******
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
7>>> NULL

Result:
Thus the C program to implement Queue ADT by using linked list is executed
successfully and the output is verified.
TO IMPLEMENT LIST ADT BY USING LINKED LIST
Ex No:3C

Aim:
To write a C program to implement List ADT by using linked list

Algorithm:
1. Create the header file Llist.h header file and we are include there header file into
the main function program by through #include<Llist.h>
2. Write function for all the basic operations of list - create(), insert(), deletion(),
search(), display().
3. By using Switch case, select create() operation to create the list.
List Will be in the form: A1, A2, A3, .... An
First Element of the List: A1
Last Element of the List: An
ith Element of the List: Ai ,
Position of Element Ai : i , Position ranges from 0 to N
Size of the List: N
Empty List: If Size of the list is Zero (i.e N=0), it is Empty List.
Precedes and Succeeds: For any list except empty list, we say that Ai+1
follows (or succeeds) Ai (i<N) and that Ai-1 precedes Ai (i>1)
4. Similarly, by using Switch case, select insert() operation to insert element in the list.
Insert x at position p in list L
If p = END(L), insert x at the end
If L does not have position p, result is undefined
5. Similarly, by using Switch case, select delete() function is used to remove the
element from the list.
delete element at position p in L
undefined if p = END(L) or does not exist
6. Similarly, by using Switch case, select search() function is used to retrieve the
required element from the list if it is available.
returns element at position p on L
undefined if p does not exist or p = END(L)
7. Similarly, by using Switch case, select display() operation to display all element of
the list
print the elements of L in order of occurrence
8. Close the program
PROGRAM:

#include<stdlib.h>
#include<stdio.h>
struct linked_list
{
int number;

struct linked_list *next;


};

typedef struct linked_list node;


node *head=NULL, *last=NULL;

void create_linked_list();
void print_linked_list();
void insert_at_last(int value);
void insert_at_first(int value);
void insert_after(int key, int value);
void delete_item(int value);
void search_item(int value);

int main()
{
int key, value;

//Create a linked list


printf("Create Linked List\n");
create_linked_list();
print_linked_list();

//Insert value at last position to existing Linked List


printf("\nInsert new item at last\n");
scanf("%d", &value);
insert_at_last(value);
print_linked_list();

//Insert value at first position to existing Linked List


printf("\nInsert new item at first\n");
scanf("%d", &value);
insert_at_first(value);
print_linked_list();

//Insert value after a defined value to existing Linked List


printf("\nEnter a KEY (existing item of List), after that you want to insert a value\n");
scanf("%d", &key);
printf("\nInsert new item after %d KEY\n", key);
scanf("%d", &value);
insert_after(key, value);
print_linked_list();

//Search an item from Linked List


printf("\nEnter an item to search it from List\n");

scanf("%d", &value);
search_item(value);

//Delete value from List


printf("\nEnter a value, which you want to delete from list\n");
scanf("%d", &value);
delete_item(value);
print_linked_list();

return 0;
}

/*
User Defined Functions
*/
void create_linked_list()
{
int val;

while(1)
{
printf("Input a number. (Enter -1 to exit)\n");

scanf("%d", &val);

if(val==-1)
break;

insert_at_last(val);
}

void insert_at_last(int value)


{
node *temp_node;
temp_node = (node *) malloc(sizeof(node));

temp_node->number=value;
temp_node->next=NULL;

//For the 1st element


if(head==NULL)
{
head=temp_node;
last=temp_node;
}

else
{
last->next=temp_node;
last=temp_node;
}

}
void insert_at_first(int value)
{
node *temp_node = (node *) malloc(sizeof(node));

temp_node->number=value;
temp_node->next = head;

head = temp_node;
}

void insert_after(int key, int value)


{
node *myNode = head;
int flag = 0;

while(myNode!=NULL)
{
if(myNode->number==key)
{
node *newNode = (node *) malloc(sizeof(node));
newNode->number = value;
newNode->next = myNode->next;
myNode->next = newNode;

printf("%d is inserted after %d\n", value, key);

flag = 1;

break;
}
else
myNode = myNode->next;
}

if(flag==0)
printf("Key not found!\n");

}
void delete_item(int value)
{
node *myNode = head, *previous=NULL;
int flag = 0;

while(myNode!=NULL)
{
if(myNode->number==value)
{
if(previous==NULL)
head = myNode->next;
else
previous->next = myNode->next;

printf("%d is deleted from list\n", value);

flag = 1;
break;
}
previous = myNode;
myNode = myNode->next;
}

if(flag==0)
printf("Key not found!\n");
}
void search_item(int value)
{
node *searchNode = head;
int flag = 0;

while(searchNode!=NULL)
{
if(searchNode->number==value)
{
printf("%d is present in this list. Memory address is %d\n", value, searchNode);
flag = 1;
break;
}

else
searchNode = searchNode->next;
}

if(flag==0)
printf("Item not found\n");

}
void print_linked_list()
{
printf("\nYour full linked list is\n");

node *myList;
myList = head;

while(myList!=NULL)
{
printf("%d ", myList->number);

myList = myList->next;
}
puts("");
}
OUTPUT:
List Adt Using Linked List
1.Create
2.Insert
3.Delete
4.MakeEmpty
5.Find
6.IsEmpty
7.Display
8.Deletelist
9.Exit
Enter ur Option: 1
List is Created.
Enter ur Option: 2
Enter the value: 100
Enter the Option: 2
Enter the value: 200
Enter the Option: 2
Enter the value: 300
Enter the Option: 2
Enter the value: 400
Enter the Option: 2
Enter the value: 500
Enter the Option: 7
100
200
300
400
500
Enter the Option: 3
Enter the value to delete: 200
Enter the Option: 7
100
300
400
500
Enter the Option: 5
Enter the value to Find: 400
Element present in the list
Enter the Option: 6
List contains some Elements
Enter the Option: 4
Now list is empty

Result:

Thus the C program to implement List ADT by using linked list is executed
successfully and the output is verified.
EX . No: 4a APPLICATION OF STACK

DATE

Aim:
To write a C program to convert infix expression to postfix expression

Algorithm:

1. Push “(“onto Stack, and add “)” to the end of X.


2. Scan X from left to right and repeat Step 3 to 6 for each element of X until
the Stack is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it onto Stack.
5. If an operator is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of
Stack) which has the same precedence as or higher precedence than
operator.
2. Add operator to
Stack. [End of If]
6. If a right parenthesis is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of
Stack) until a left parenthesis is encountered.
2. Remove the left
Parenthesis. [End of If]
[End of If]
7. END.
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20
char stack[MAX];
int top=-1;
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':return 2;
break;
case '*':
case '/':return 4;
break;
case '^':
case ':return 6;
break;
case '(':
case ')':
case '#':return 1;
break;
}
}

int isoperator(char symbol)


{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case ':
case '(':
case ')':return 1;
break;
default:return 0;
}
}
void convertip(char infix[],char postfix[])
{
int i,symbol,j=0;
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
{
postfix[j]=symbol;
j++;
}
else{
if(symbol=='(')push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop();//pop out (.
}
else{
if(prcd(symbol)>prcd(stack[top]))
push(symbol);
else{
while(prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
}
push(symbol);
}//end of else.
}//end of else.
}//end of else.
}//end of for.
while(stack[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';//null terminate string.
}
void main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string:\n");
gets(infix);
convertip(infix,postfix);
printf("The corresponding postfix string is:\n");
puts(postfix);
getch();
}

void push(char item)


{
top++;
stack[top]=item;
}

char pop()
{
char a;
a=stack[top];
top--;
return a;
}

OUTPUT:
Enter Infix expression : A+(B*C-(D/E^F)*G)*H
Postfix Expression: ABC*DEF^/G*-H*+Fir

Enter Infix expression : (3^2*5)/(3*2-3)+5


Postfix Expression: 32^5*32*3-/5+

Result:
Thus the C program to convert infix to postfix is executed successfully and the
output is verified.
EX No: 4b C PROGRAM TO ADD TWO POLYNOMIALS

DATE:

Aim:
To write a C program to add two polynomials

Algorithm:
Algorithm to add two polynomials using linked list is as
follows:-Let p and q be the two polynomials represented
by linked lists
1. While p and q are not null, repeat step 2.
2. If powers of the two terms are equal then if the terms do not cancel
then insert the sum of the terms into the sum Polynomial
Advance pAdvance q

Else if the power of the first polynomial> power of second


Then insert the term from first polynomial into sum polynomial Advance p
Else insert the term from second polynomial into sum polynomial Advance q
3. Copy the remaining terms from the non empty polynomial into the sum polynomial.
4.The third step of the algorithm is to be processed till the end of the polynomials has
not been reached.
PROGRAM:
#include <stdio.h>
typedef struct pnode
{
float coef;
int exp;
struct pnode *next;
}p;
p *getnode();
void main()
{

p *p1,*p2,*p3;

p *getpoly(),*add(p*,p*);

void display(p*);
clrscr();
printf(“\n enter first polynomial”);
p1=getpoly();
printf(“\n enter second polynomial”);
p2=getpoly();
printf(“\nthe first polynomial is”);
display(p1);
printf(“\nthe second polynomial is”);
display(p2);
p3=add(p1,p2);
printf(“\naddition of two polynomial is :\n”);
display(p3);
}
p *getpoly()
{
p *temp,*New,*last;
int flag,exp;
char ans;
float coef;
temp=NULL;
flag=1;
printf(“\nenter the polynomial in descending order of exponent”);
do
{
printf(“\nenter the coef & exponent of a term”);
scanf(“%f%d”,&coef,&exp);
New=getnode();
if(New==NULL)
printf(“\nmemory cannot be allocated”);
New->coef=coef;
New->exp=exp;
if(flag==1)
{
temp=New;
last=temp;
flag=0;
}
else
{
last->next=New;
last=New;
}
printf(“\ndou want to more terms”);
ans=getch();
}
while(ans==’y');
return(temp);

}
p *getnode()
{
p *temp;

temp=(p*) malloc (sizeof(p));


temp->next=NULL;
return(temp);
}
void display(p*head)
{
p*temp;
temp=head;
if(temp==NULL)
printf(“\npolynomial empty”);
while(temp->next!=NULL)
{
printf(“%0.1fx^%d+”,temp->coef,temp->exp);
temp=temp->next;
}
printf(“\n%0.1fx^%d”,temp->coef,temp->exp);
getch();
}
p*add(p*first,p*second)
{
p *p1,*p2,*temp,*dummy;
char ch;
float coef;
p *append(int,float,p*);
p1=first;
p2=second;
temp=(p*)malloc(sizeof(p));
if(temp==NULL)
printf(“\nmemory cannot be allocated”);
dummy=temp;
while(p1!=NULL&&p2!=NULL)
{
if(p1->exp==p2->exp)
{
coef=p1->coef+p2->coef;
temp=append(p1->exp,coef,temp);
p1=p1->next;
p2=p2->next;
}
else
if(p1->exp>p2->exp)
{
coef=p1->coef;
temp=append(p1->exp,coef,temp);
p1=p1->next;
}
else
if(p1->exp<p2->exp)
{
coef=p1->coef;
temp=append(p1->exp,coef,temp);
p1=p1->next;
}

}
while(p1!=NULL)
{
temp=append(p1->exp,p1->coef,temp);
p1=p1->next;
}
while(p2!=NULL)
{
temp=append(p2->exp,p2->coef,temp);
p2=p2->next;
}
temp->next=NULL;
temp=dummy->next;
free(dummy);
return(temp);
}
p*append(int Exp,float Coef,p*temp)
{
p*New,*dum;
New=(p*)malloc(sizeof(p));
if(New==NULL)
printf(“\ncannot be allocated”);
New->exp=Exp;
New->coef=Coef;
New->next=NULL;
dum=temp;
dum->next=New;
dum=New;
return(dum);
}
OUTPUT:
Create 1st expression
Enter Coeff:1
Enter Pow:2
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0
Stored the 1st expression
The polynomial expression is:
1x^2
Create 2nd expression
Enter Coeff:2
Enter Pow:3
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0
Stored the 2nd expression
The polynomial expression is:
2x^3

The polynomial expression is:


2x^3 + 1x^2
Add two more expressions? (Y = 1/N = 0): 0
...Program finished with exit code 0

Result:
Thus the C program to implement polynomial addition by using linked list is
executed successfully and the output is verified.
Ex.No:5a IMPLEMENTATION OF BINARY TREE & ITS
OPERATIONS

DATE:

Aim:
To write a C program to implement binary tree and its operation

Algorithm:
1. Start the program
2. Create a tree
3. Perform the Insertion, Deletion and Search operation
4. Display Preorder, Postorder, Inorder traversal data
5. Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *left,*right;
};
struct node *root;
void insert(int x)
{
struct node *p,*previous,*current;
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{

printf("\n Out of memory");


}
p->data=x;
p->left=NULL;
p->right=NULL;
if(root=NULL)
{
root=p;
return;
}
previous=NULL;
current=root;
while(current!=NULL)
{
previous=current;
if(p->data<current->data)
current=current->left;
else
current=current->right;
}
if(p->data<previous->data)
previous->left=p;
else
previous->right=p;
}
void inorder(struct node *t)
{
if (t!=NULL)
{
inorder(t->left);
printf("\n %5d",t->data);
inorder (t->right);
}
}
void del(int x)
{
int tright=0,tleft=0;
struct node *ptr=root;
struct node *parent=root;
struct node *t1=root;
struct node *temp=root;
while(ptr!=NULL&& ptr->data!=x)
{
parent=ptr;
if (x<ptr->data)
ptr=ptr->left;
else
ptr=ptr->right;
}
if (ptr==NULL)
{
printf("\n Delete element not found");
return ;
}
else if(t1->data==x && (t1->left ==NULL || t1->right==NULL))
if(t1->left==NULL)
t1=t1->right;
else
t1=t1->left;
else if (ptr->left==NULL)
if (x<parent->data)
parent->left=ptr->right;
else
parent->right=ptr->right;
else if (ptr->right==NULL)
if (x<parent->data)
parent->left=ptr->left;
else
parent->right=ptr->left;
else
{
temp=ptr;
parent=ptr;
if((ptr->left)>=(ptr->right))
{
ptr=ptr->left;
while(ptr->right!=NULL)
{
tright=1;
parent=ptr;
ptr=ptr->right;
}
temp->data=ptr->data;
if(tright)
parent->right=ptr->left;
else
parent->left=ptr->left;
}
else
{
ptr=ptr->right;
while (ptr->left!=NULL)
{
tleft=1;
parent=ptr;
ptr=ptr->left;
}
temp->data=ptr->data;
if(tleft)
parent->left=ptr->right;
else
parent->right=ptr->right;
}
free(ptr);
}
}

void main()
{
int op,n,srchno;
root=(struct node *)malloc(sizeof(struct node));
root->data=30;
root->right=root->left=NULL;
clrscr();
do
{
printf("\n 1.Insertion");
printf("\n 2.Deletion");
printf("\n 3.Inorder");
printf("\n 4.Quit");
printf("\n Enter your choice\n");
scanf("%d",&op);
switch (op)
{
case 1: printf("\n Enter the element to insert\n");
scanf("%d",&n);
insert(n);
break;
case 2: printf("\n Enter the element to be deleted\n");
scanf("%d",&srchno);
del(srchno);
break;
case 3: printf("\n The inorder elements are\n");
inorder(root);
getch();
break;
default: exit(0);
}
}while(op<4);
getch();
}

OUTPUT

> IN ORDER -
> 0 2 2 8 9 9 16 17 18 19 19 20 20 21 21 22 23 26 28 29 35 37 40 41 45 50 51 54 62 63 6
3 64 66 66 68 69 7
0 71 73 75 76 76 78 79 79 80 83 83 85 86 89 91 91 95 96 96 101 101 101 102 103 104 10
4 104 106 107 108 108 109 111 112
113 114 115 115 115 116 117 117 119 120 123 124 125 127 127 129 129 129 130 130 1
34 134 137 139 139 140 142 143 143

> PRE ORDER -


> 127 101 21 21 2 2 0 8 20 18 16 9 9 17 19 19 20 96 51 22 35 26 23 28 29 37 45 40 41 5
0 79 76 66 66 63 5
4 63 62 64 73 68 69 71 70 76 75 79 78 89 86 80 83 83 85 91 91 95 96 101 101 116 108 1
02 107 106 104 104 103 104 108 11
3 112 109 111 115 115 115 114 120 117 117 119 127 125 124 123 129 129 129 140 137
134 134 130 130 139 139 143 142 143

> POST ORDER -


> 0 2 9 9 17 16 19 20 19 18 20 8 2 21 23 29 28 26 41 40 50 45 37 35 22 62 63 54 64 63 6
6 70 71 69 68 75
76 73 66 78 79 76 83 85 83 80 86 91 96 95 91 89 79 51 101 101 96 21 104 103 104 104
106 108 107 102 111 109 112 114 1
15 115 115 113 108 117 119 117 123 124 125 127 120 116 101 129 129 130 130 134 134
139 139 137 143 142 143 140 129 127

> TEST SEARCH:


-2
-8
-9
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 26
- 28
- 29
- 35
- 37

- 40
- 41
- 45
- 50
- 51
- 54
- 62
- 63
- 64
- 66
- 68
- 69
- 70
- 71
- 73
- 75
- 76
- 78
- 79
- 80
- 83
- 85
- 86
- 89
- 91
- 95
- 96

<SUCCESS> = 43 <FAILED> = 57

...Program finished with exit code 0

Result:
Thus the C programs to implement Binary tree is executed successfully and output
is verified.
Ex.No:6 IMPLEMENTATION OF BINARY SEARCH TREE

DATE

Aim:
To write a C program to implement binary search tree

Algorithm:
1. Start the program
2. Create a tree
3. Perform the Insertion, Deletion and Search operation
4. Display Preorder, Postorder, Inorder traversal data
5. Stop the program
PROGRAM:

#include <stdio.h>
#include <stdlib.h>
struct treeNode {
int data;
struct treeNode *left, *right;
};
struct treeNode *root = NULL;
/* create a new node with the given data */
struct treeNode* createNode(int data) {
struct treeNode *newNode;
newNode = (struct treeNode *) malloc(sizeof (struct treeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return(newNode);
}
/* insertion in binary search tree */
void insertion(struct treeNode **node, int data) {
if (*node == NULL) {
*node = createNode(data);
} else if (data < (*node)->data) {
insertion(&(*node)->left, data);
} else if (data > (*node)->data) {
insertion(&(*node)->right, data);
}
}

/* deletion in binary search tree */


void deletion(struct treeNode **node, struct treeNode **parent, int data) {
struct treeNode *tmpNode, *tmpParent;
if (*node == NULL)
return;
if ((*node)->data == data) {
/* deleting the leaf node */

if (!(*node)->left && !(*node)->right) {


if (parent) {
/* delete leaf node */
if ((*parent)->left == *node)
(*parent)->left = NULL;
else
(*parent)->right = NULL;
free(*node);
} else {
/* delete root node with no children */
free(*node);
}
/* deleting node with one child */
} else if (!(*node)->right && (*node)->left) {
/* deleting node with left child alone */
tmpNode = *node;
(*parent)->right = (*node)->left;
free(tmpNode);
*node = (*parent)->right;
} else if ((*node)->right && !(*node)->left) {
/* deleting node with right child alone */
tmpNode = *node;
(*parent)->left = (*node)->right;
free(tmpNode);
(*node) = (*parent)->left;
} else if (!(*node)->right->left) {
/*
* deleting a node whose right child
* is the smallest node in the right
* subtree for the node to be deleted.
*/
tmpNode = *node;
(*node)->right->left = (*node)->left;
(*parent)->left = (*node)->right;
free(tmpNode);
*node = (*parent)->left;
} else {
/*
* Deleting a node with two children.
* First, find the smallest node in
* the right subtree. Replace the
* smallest node with the node to be
* deleted. Then, do proper connections
* for the children of replaced node.
*/
tmpNode = (*node)->right;
while (tmpNode->left) {
tmpParent = tmpNode;
tmpNode = tmpNode->left;
}
tmpParent->left = tmpNode->right;
tmpNode->left = (*node)->left;
tmpNode->right =(*node)->right;

free(*node);
*node = tmpNode;
}
} else if (data < (*node)->data) {
/* traverse towards left subtree */
deletion(&(*node)->left, node, data);
} else if (data > (*node)->data) {
/* traversing towards right subtree */
deletion(&(*node)->right, node, data);
} }
/* search the given element in binary search tree */
void findElement(struct treeNode *node, int data) {
if (!node)
return;
else if (data < node->data) {
findElement(node->left, data);
} else if (data > node->data) {
findElement(node->right, data);
} else
printf("data found: %d\n", node->data);
return;

}
void traverse(struct treeNode *node) {
if (node != NULL) {
traverse(node->left);
printf("%3d", node->data);
traverse(node->right);
}
return;
}

int main() {
int data, ch;
while (1) {
printf("1. Insertion in Binary Search Tree\n");
printf("2. Deletion in Binary Search Tree\n");
printf("3. Search Element in Binary Search Tree\n");
printf("4. Inorder traversal\n5. Exit\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
while (1) {
printf("Enter your data:");
scanf("%d", &data);
insertion(&root, data);
printf("Continue Insertion(0/1):");
scanf("%d", &ch);
if (!ch)
break;
}
break;
case 2:
printf("Enter your data:");
scanf("%d", &data);
deletion(&root, NULL, data);
break;
case 3:
printf("Enter value for data:");
scanf("%d", &data);
findElement(root, data);
break;
case 4:
printf("Inorder Traversal:\n");
traverse(root);
printf("\n");
break;
case 5:
exit(0);
default:
printf("u've entered wrong option\n");
break;
}
}
return 0;

OUTPUT:

cc tree43.c $
a.out
OPERATIONS -
--
1 - Insert an element into tree
2 - Delete an element from the tree
3 - Inorder Traversal
4 - Preorder Traversal
5 - Postorder Traversal
6 - Exit

Enter your choice : 1


Enter data of node to be inserted : 40

Enter your choice : 1


Enter data of node to be inserted : 20

Enter your choice : 1


Enter data of node to be inserted : 10

Enter your choice : 1


Enter data of node to be inserted : 30

Enter your choice : 1


Enter data of node to be inserted : 60

Enter your choice : 1


Enter data of node to be inserted : 80

Enter your choice : 1


Enter data of node to be inserted : 90
Enter your choice : 3
10 -> 20 -> 30 -> 40 -> 60 -> 80 -> 90 >40

/\
/ \
20 60
/\ \
10 30 80
\
90

Result:
Thus the C program to implement Binary search tree is executed successfully and
output is verified.
Ex.No:7 IMPLEMENTATION OF AVL TREES

DATE:

Aim:
To write a C program to implement AVL trees

Algorithm:
1. Declare the structure of node

2. Initialize the balance factor, all basic operations of AVL tree

3. Consider the root node is NULL

4. Do rotations if the balance factor is not in normalized

5. User must choose one option from five choices given in the menu

6. Perform all the operations

7. Stop the program


PROGRAM:

#include<stdio.h>
typedef struct node
{
int data;
struct node *left,*right;
int ht;
}node;
node *insert(node *,int);
node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);
int main()
{
node *root=NULL;
int x,n,i,op;
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;

case 2: printf("\nEnter a data:");


scanf("%d",&x);
root=insert(root,x);
break;
case 3: printf("\nEnter a data:");
scanf("%d",&x);
root=Delete(root,x);
break;

case 4: printf("\nPreorder sequence:\n");


preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n");
break;
}
}while(op!=5);
return 0;
}
node * insert(node *T,int x)
{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}

T->ht=height(T);
return(T);
}
node * Delete(node *T,int x)
{
node *p;
if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;

while(p->left!= NULL)
p=p->left;

T->data=p->data;
T->right=Delete(T->right,p->data);

if(BF(T)==2)//Rebalance during windup


if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
int height(node *T)
{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

if(lh>rh)
return(lh);

return(rh);
}

node * rotateright(node *x)


{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * rotateleft(node *x)


{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);

return(y);
}

node * RR(node *T)


{
T=rotateleft(T);
return(T);
}
node * LL(node *T)
{
T=rotateright(T);
return(T);
}

node * LR(node *T)


{
T->left=rotateleft(T->left);
T=rotateright(T);

return(T);
}

node * RL(node *T)


{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}

int BF(node *T)


{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

return(lh-rh);
}

void preorder(node *T)


{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}

void inorder(node *T)


{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}

OUTPUT:

1) Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:1
Enter no. of elements:4
Enter tree data:7 12 4 9
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:4
Preorder sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)
Inorder sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:3
Enter a data:7
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:4
Preorder sequence:
9(Bf=0)4(Bf=0)12(Bf=0)
Inorder sequence:
4(Bf=0)9(Bf=0)12(Bf=0)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:5

Result:
Thus the C program to implement AVL tree is executed successfully and output is verified.
Ex.No:8 IMPLEMENTATION OF HEAP USING PRIORITY QUEUE

Aim:
To write a C program to implement heap data structure
Algorithm:
1. Start the program
2. Initially, declare n=0 for number of nodes in the heap’
3. By using while, create a menu for all operations of heaps
4. Perform all the operation and display the result
5. Stop the program
PROGRAM:

#include<stdio.h>
struct heapstruct
{
int capacity;
int size;
int *a;
};
typedef struct heapstruct *pq;
pq initialize(int maxa,int mindata)
{
pq h;
h=(struct heapstruct*)malloc(sizeof(struct heapstruct));
if(h==NULL)
printf(“\nOut of Space”);
h->a=(int*)malloc((maxa+1)*sizeof(int));
h->capacity=maxa;
h->size=0;
h->a[0]=mindata;
return h;
}
void insert(int x,pq h)
{
int i;
if(h->size==h->capacity)
{
printf(“\nFull”);
}
else
{
for(i=++h->size;h->a[i/2]>x;i=i/2)
{
h->a[i]=h->a[i/2];
}
h->a[i]=x;
}
}
int delmin(pq h)
{
int i,mina,lasta,child;
if(h->size==0)
{
return(h->a[0]);
}
else
{
mina=h->a[1];
lasta=h->a[h->size--];
for(i=1;i*2size;i=child)
{
child=i*2;
if(child!=h->size && h->a[child+1]a[child])
child++;
if(lasta>h->a[child])
{
h->a[i]=h->a[child];
}
else
break;
}
h->a[i]=lasta;
return mina;
}
}
void display(pq h)
{
int i;
for(i=1;isize;i++)
{
printf(“\nThe data is: %d”,h->a[i]);
}
}
void main()
{
pq h;int x,y,z,u,v;char ch;
clrscr();
printf(“\nEnter the maximum number of elements for the Priority Queue:”);
scanf(“%d”,&x);
printf(“\nEnter the minimum element :”);
scanf(“%d”,&y);
h=initialize(x,y);
menu:
printf(“\nPriority Queue”);
printf(“\n1.Insert\n2.Delete\n3.Display\n4.Exit”);
scanf(“%d”,&u);
switch(u)
{
case 1:printf(“Enter the Data:”);
scanf(“%d”,&z);
insert(z,h);
break;
case 2:v=delmin(h);
printf(“\nThe deleted element is: %d”,v);
break;
case 3:display(h);
break;
case 4:exit(0);
}
goto menu;
}
OUTPUT:
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 1
Enter the element to be inserted to the list : 30
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 1
Enter the element to be inserted to the list : 50
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 1
Enter the element to be inserted to the list : 70
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 2
Enter the elements to be deleted from the list: 10
10 not found in heap list
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 2
Enter the elements to be deleted from the list: 50
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 1
Enter the element to be inserted to the list : 100
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 3
100 30 70
1.Insert the element
2.Delete the element
3.Display all elements
4.Quit
Enter your choice : 4

Result:
Thus the C programs to implement heap is executed successfully and output is verified.
Ex: 9A GRAPH REPRESENTATIONS

Date:

Aim:
To write a C program implement adjacent matrix and adjacency list

Algorithm:
1. Create a graph with getting no. of vertices and no. of edges
2. Implement adjacency matrix
3. Implement adjacency list
4. Close the program
PROGRAM:
# include < stdio.h >
# include < conio.h >
void main()
{
int option;
clrscr();
do
{
printf("\n A Program to represent a Graph by using an ");
printf("Adjacency Matrix method \n ");
printf("\n 1. Directed Graph ");
printf("\n 2. Un-Directed Graph ");
printf("\n 3. Exit ");
printf("\n\n Select a proper option : ");
scanf("%d", &option);
switch(option)
{
case 1 : dir_graph();
break;
case 2 : undir_graph();
break;
case 3 : exit(0);
} // switch
}while(1);
} // main
int dir_graph()
{
int adj_mat[50][50];
int n;
int in_deg, out_deg, i, j;
printf("\n How Many Vertices ? : ");
scanf("%d", &n);
read_graph (adj_mat, n);
printf("\n Vertex \t In_Degree \t Out_Degree \t Total_Degree ");
for (i = 1; i < = n ; i++ )
{
in_deg = out_deg = 0;
for ( j = 1 ; j <= n ; j++ )
{
if ( adj_mat[j][i] == 1 )
in_deg++;
} // for
for ( j = 1 ; j <= n ; j++ )
if (adj_mat[i][j] == 1 )
out_deg++;
printf("\n\n %5d\t\t\t%d\t\t%d\t\t%d\n\n",i,in_deg,out_deg,in_deg+out_deg);
} // for
return;
} // dir_graph
int undir_graph()
{
int adj_mat[50][50];
int deg, i, j, n;
printf("\n How Many Vertices ? : ");
scanf("%d", &n);
read_graph(adj_mat, n);
printf("\n Vertex \t Degree ");
for ( i = 1 ; i <= n ; i++ )
{
deg = 0;
for ( j = 1 ; j <= n ; j++ )
if ( adj_mat[i][j] == 1)
deg++;
printf("\n\n %5d \t\t %d\n\n", i, deg);
} // for
return;
} // undir_graph

int read_graph ( int adj_mat[50][50], int n )


{
int i, j;
char reply;
for ( i = 1 ; i <= n ; i++ )
{
for ( j = 1 ; j <= n ; j++ )
{
if ( i == j )
{
adj_mat[i][j] = 0;
continue;
} // if
printf("\n Vertices %d & %d are Adjacent ? (Y/N) :",i,j);
flushall();
scanf("%c", &reply);
if ( reply == 'y' || reply == 'Y' )
adj_mat[i][j] = 1;
else
adj_mat[i][j] = 0;
} // for
} // for
return;
} // read_graph
OUTPUT:
A Program to represent a Graph by using an Adjacency Matrix method

1. Directed Graph
2. Un-Directed Graph
3. Exit

Select a proper option :


How
Many Vertices ? :
Vertices 1 & 2 are Adjacent ? (Y/N) : N
Vertices 1 & 3 are Adjacent ? (Y/N) : Y
Vertices 1 & 4 are Adjacent ? (Y/N) : Y
Vertices 2 & 1 are Adjacent ? (Y/N) : Y
Vertices 2 & 3 are Adjacent ? (Y/N) : Y
Vertices 2 & 4 are Adjacent ? (Y/N) : N
Vertices 3 & 1 are Adjacent ? (Y/N) : Y
Vertices 3 & 2 are Adjacent ? (Y/N) : Y
Vertices 3 &4 are Adjacent ? (Y/N) : Y
Vertices 4 &1 are Adjacent ? (Y/N) : Y
Vertices 4 &2 are Adjacent ? (Y/N) : N
Vertices 4 &3 are Adjacent ? (Y/N) : Y
Vertex In_Degree Out_Degree Total_Degree
1 2 0 2

2 1 2 3

3 0 1 1

4 1 1 2

A Program to represent a Graph by using an Adjacency List method

1. Directed Graph
2. Un-Directed Graph
3. Exit
Select a proper option :
How Many Vertices ? :
Vertices 1 & 2 are Adjacent ? (Y/N) : N
Vertices 1 & 3 are Adjacent ? (Y/N) : Y
Vertices 1 & 4 are Adjacent ? (Y/N) : Y
Vertices 2 & 1 are Adjacent ? (Y/N) : Y
Vertices 2 & 3 are Adjacent ? (Y/N) : Y
Vertices 2 & 4 are Adjacent ? (Y/N) : N
Vertices 3 & 1 are Adjacent ? (Y/N) : Y
Vertices 3 & 2 are Adjacent ? (Y/N) : Y
Vertices 3 & 4 are Adjacent ? (Y/N) : Y
Vertices 4 & 1 are Adjacent ? (Y/N) : Y
Vertices 4 & 2 are Adjacent ? (Y/N) : N
Vertices 4 & 3 are Adjacent ? (Y/N) : Y

Result:

Thus the C programs to implement graph representation, Adjacency matrix and Adjacency
List are executed successfully and the outputs are verified.
Ex: 9B GRAPH TRAVERSAL

Date:

Aim:
To write a C program implement DFS and BFS graph traversal.

Algorithm:
DFS
1. Define a Stack of size total number of vertices in the graph.
2. Select any vertex as starting point for traversal. Visit that vertex and push it on
to the Stack.
3. Visit any one of the adjacent vertex of the verex which is at top of the stack
which is not visited and push it on to the stack.
4. Repeat step 3 until there are no new vertex to be visit from the vertex on top of
the stack.
5. When there is no new vertex to be visit then use back tracking and pop
one vertex from the stack.
6. Repeat steps 3, 4 and 5 until stack becomes Empty.
7. When stack becomes Empty, then produce final spanning tree by removing
unused edges from the graph

BFS

1. Define a Queue of size total number of vertices in the graph.


2. Select any vertex as starting point for traversal. Visit that vertex and insert it
into the Queue.
3. Visit all the adjacent vertices of the verex which is at front of the Queue which
is not visited and insert them into the Queue.
4. When there is no new vertex to be visit from the vertex at front of the Queue then
delete that vertex from the Queue.
5. Repeat step 3 and 4 until queue becomes empty.
6. When queue becomes Empty, then produce final spanning tree by removing
unused edges from the graph
PROGRAM:
#include<stdio.h>
int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();
void main()
{
int n,i,s,ch,j;

char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S");
printf("\nENTER YOUR CHOICE");
scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);
switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}

//**************BFS(breadth-first search) code**************//


void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)

printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n); }

void add(int item)


{
if(rear==19)
printf("QUEUE FULL");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}

//***************DFS(depth-first search) code******************//


void dfs(int s,int n)
{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}

for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
else
{
k=stack[top--];
return(k);
}
}

OUTPUT

Depth First Traversal (starting from vertex 2)


2013

Breadh First Traversal (starting from vertex 2)

2031

Result:
Thus the C program to implement DFS and BFS are executed successfully and the
outputs are verified.
IMPLEMENTATION OF SEARCHING ALGORITHMS
Ex: 10
LINEAR SEARCH AND BINARY SEARCH

Date

Aim:
To write a C Program to implement different searching techniques – Linear and
Binary
search.
Algorithm:
Linear Search:

1. Read the search element from the user


2. Compare, the search element with the first element in the list.
3. If both are matching, then display "Given element found!!!" and terminate the
function
4. If both are not matching, then compare search element with the next element in the
list.
5. Repeat steps 3 and 4 until the search element is compared with the last element in the
list.
6. If the last element in the list is also doesn't match, then display "Element not
found!!!" and terminate the function.

Binary search is implemented using following steps...

1. Read the search element from the user


2. Find the middle element in the sorted list
3. Compare, the search element with the middle element in the sorted list.
4. If both are matching, then display "Given element found!!!" and
terminate the function
5. If both are not matching, then check whether the search element is
smaller or larger than middle element.
6. If the search element is smaller than middle element, then repeat steps 2,
3, 4 and 5 for the left sublist of the middle element.
7. If the search element is larger than middle element, then repeat steps 2, 3,
4 and 5 for the right sublist of the middle element.
8. Repeat the same process until we find the search element in the list or
until sublist contains only one element.
9. If that element also doesn't match with the search element, then display
"Element not found in the list!!!" and terminate the function.
PROGRAM:
#include <stdio.h>
/* Function for sequential search */
void sequential_search(int array[],int size,int n)
{
int i;
for(i =0; i < size; i++)
{

if(array[i]== n)
{
printf("%d found at location %d.\n", n, i+1);
break;
}
}
if(i == size)
printf("Not found! %d is not present in the list.\n", n);
}
/* End of sequential_search() */
/* Function for binary search */
void binary_search(int array[],int size,int n)
{
int i, first, last, middle;
first =0;
last = size -1;
middle =(first+last)/2;

while(first <= last){


if(array[middle]< n)
first = middle +1;
elseif(array[middle]== n){
printf("%d found at location %d.\n", n, middle+1);
break;
}
else
last = middle -1;

middle =(first + last)/2;


}
if( first > last )
printf("Not found! %d is not present in the list.\n", n);
}
/* End of binary_search() */

/* The main() begins */


int main()
{
int a[200], i, j, n, size;
printf("Enter the size of the list:");
scanf("%d",&size);
printf("Enter %d Integers in ascending order\n", size);
for(i =0; i < size; i++)
scanf("%d",&a[i]);
printf("Enter value to find\n");
scanf("%d",&n);
printf("Sequential search\n");
sequential_search(a, size, n);
printf("Binary search\n");

binary_search(a, size, n);


return0;
}

OUTPUT:

Linear Search
Enter size of the list: 4
Enter any 4 integer values: 4 8 1 9
Enter the element to be Search: 9

Element is found at 3 index

...Program finished with exit code 10

Binary Search
Enter the size of the list: 4
Enter 4 integer values in Assending order
1 6 9 12

Enter value to be search: 9


Element found at index 2.

Result:
Thus the C programs to implement linear search and binary search are executed
successfully and outputs are verified.
Ex: 11 IMPLEMENTATION OF SORTING ALGORITHMS –
BUBBLE SORT, RADIX SORT, SHELL SORT
Date:

Aim:
To write a C program to implement different sorting algorithms - Bubble Sort,
Radix Sort, Shell Sort

Algorithm:
Bubble Sort:
1. Read the value of n
2. Get the inputs for array[n].
3. Implement Bubble sort
Step 1: Repeat Steps 2 and 3 for i=1 to 10
Step 2: Set j=1
Step 3: Repeat while j<=n
(A) if a[i] < a[j]
Then interchange a[i] and a[j] [End
of if]
(B) Set j = j+1
[End of Inner Loop]
[End of Step 1 Outer Loop]
Step 4: Exit
4. Stop the program

Shell Sort
1. Read the value of n
2. Get the inputs for array[n].
3. Implement shell sort
4. Stop the program

Radix Sort
1. Read the value of n
2. Get the inputs for array[n].
3. Implement radix sort
4. Stop the program
Bubble Sort:
#include<stdio.h>
int *a[100],i,j,item;
void main()
{
void sort(),display();
int i;
clrscr();
printf("\n Enter the number of elements in the first array\n");
scanf("%d",&item);
printf("\n Enter %d numbers\n",item);
for(i=0;i<item;++i)
scanf("%d",&a[i]);
sort();
display();
}
void sort()
{
int swap=1,*temp;
for(i=0;i<item && swap==1;++i)
{
swap=0;
for(j=0;j<item-(i+1);++j)
if (a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
swap=1;
}
}
}
void display()
{
printf("\n Sorted elements are:\n");
for(i=0;i<item;++i)
printf("%d\n",a[i]);
getch();
}
Radix Sort:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *start = NULL;
void radix_sort();
int larger_digit();
int digit_finder(int number, int k);
int main()
{
struct node *temp, *x;
int count, limit, element;
printf("\nEnter Total Number of Elements:\t");
scanf("%d", &limit);
for(count = 0; count < limit; count++)
{
printf("Element No. %d:\t", count + 1);
scanf("%d", &element);
temp = malloc(sizeof(struct node));
temp->data = element;
temp->link = NULL;
if(start == NULL)
{
start = temp;
}
else
{
x = start;
while(x->link != NULL)
{
x = x->link;
}
x->link = temp;
}
}
radix_sort();
printf("\nSorted List\n");
x = start;
while(x != NULL)
{
printf("%3d", x->data);
x = x->link;
}
printf("\n");
return 0;
}
void radix_sort()
{
int count, k, digit, least_significant, most_significant;
struct node *rear[10], *front[10], *p;
least_significant = 1;
most_significant = larger_digit(start);
for(k = least_significant; k <= most_significant; k++)
{
for(count = 0; count <= 9; count++)
{
rear[count] = NULL;
front[count] = NULL ;
}
for(p = start; p != NULL; p = p->link)
{
digit = digit_finder(p->data, k);
if(front[digit] == NULL)
{
front[digit] = p;
}
else
{
rear[digit]->link = p;
}
rear[digit] = p;
}
count = 0;
while(front[count] == NULL)

{
count++;
}
start = front[count];
while(count < 9)
{
if(rear[count + 1] != NULL)
{
rear[count]->link = front[count + 1];
}
else
{
rear[count + 1] = rear[count];
}
count++;
}
rear[9]->link = NULL;
}
}
int larger_digit()
{
struct node *p = start;
int temp = 0, digit = 0;
while(p != NULL)
{
if(p ->data > temp)
{
temp = p->data;
}
p = p->link ;
}
while(temp != 0)
{
digit++;
temp = temp / 10;
}
return(digit);
}

int digit_finder(int number, int k)


{
int term, count;
for(count = 1; count <= k; count++)
{
term = number % 10;
number = number / 10;
}
return(term);
}
Shell Sort:
#include<stdio.h>
voidShellSort(inta[], intn)
{
inti, j, increment, tmp;
for(increment = n/2; increment > 0; increment /= 2)
{
for(i = increment; i < n; i++)
{
tmp = a[i];
for(j = i; j >= increment; j -= increment)
{
if(tmp < a[j-increment])
a[j] = a[j-increment];
else
break;
}
a[j] = tmp;
}
}
}

intmain()
{
inti, n, a[10];
printf("Enter the number of elements :: ");
scanf("%d",&n);
printf("Enter the elements :: ");
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
ShellSort(a,n);
printf("The sorted elements are :: ");
for(i = 0; i < n; i++)
printf("%d ",a[i]);
printf("\n");
return0;
}
Output
Bubble sort
Shell sort
Enter total no. of elements : 10
Enter numbers : 36 432 43 44 57 63 94 3 5 6
Sorted array is : 3 5 6 36 43 44 57 63 94 432
Radix sort
$ gcc RadixSort.c
$ ./a.out
Enter total no. of elements : 8
Enter numbers : 802 2 24 45 66 75 90 170
Sorted array is : 2 24 45 66 75 90 170 802

Result:
Thus the C programs to implement different sorting algorithms are executed
successfully and outputs are verified.
Ex. No: 12 IMPLEMENTATION OF HASHING TABLE

DATE
Aim:
To write a C program to implement hash table

Algorithm:
1. Create a structure, data (hash table item) with key and value as data.
2. Now create an array of structure, data of some certain size (10, in this
case). But, the size of array must be immediately updated to a prime
number just greater than initial array capacity (i.e 10, in this case).
3. A menu is displayed on the screen.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop the program
PROGRAM:
#include<stdio.h>
#include<stdlib.h>

/* to store a data (consisting of key and value) in hash table array */


struct item
{
int key;
int value;
};

/* each hash table item has a flag (status) and data (consisting of key and value) */
struct hashtable_item
{

int flag;
/*
* flag = 0 : data does not exist
* flag = 1 : data exists
* flag = 2 : data existed at least once
*/

struct item *data;

};
struct hashtable_item *array;
int size =0;
int max =10;
/* initializing hash table array */
void init_array()
{

int i;
for(i =0; i < max; i++)
{
array[i].flag=0;
array[i].data= NULL;
}
}

/* to every key, it will generate a corresponding index */


int hashcode(int key)
{
return(key % max);
}

/* to insert an element in the hash table */


void insert(int key,int value)
{
int index = hashcode(key);
int i = index;

/* creating new item to insert in the hash table array */


struct item *new_item =(struct item*)malloc(sizeof(struct item));
new_item->key = key;
new_item->value = value;

/* probing through the array until we reach an empty space */


while(array[i].flag==1)
{

if(array[i].data->key == key)
{

/* case where already existing key matches the given key */


printf("\n Key already exists, hence updating its value \n");
array[i].data->value = value;
return;

i =(i +1)% max;


if(i == index)
{
printf("\n Hash table is full, cannot insert any more item \n");
return;
}

}
array[i].flag=1;
array[i].data= new_item;
size++;
printf("\n Key (%d) has been inserted \n", key);

/* to remove an element from the hash table */


void remove_element(int key)
{
int index = hashcode(key);
int i = index;

/* probing through array until we reach an empty space where not even once an element had
been present */
while(array[i].flag!=0)
{

if(array[i].flag==1&& array[i].data->key == key )


{
// case when data key matches the given key
array[i].flag=2;
array[i].data= NULL;
size--;
printf("\n Key (%d) has been removed \n", key);
return;

}
i =(i +1)% max;
if(i == index)
{
break;
}

printf("\n This key does not exist \n");

/* to display all the elements of hash table */


void display()
{
int i;
for(i =0; i < max; i++)
{
struct item *current =(struct item*) array[i].data;

if(current == NULL)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements -: \n %d (key) and %d(value) ", i, current->key,
current->value);

int size_of_hashtable()
{
return size;
}

void main()

int choice, key, value, n, c;


clrscr();

array =(struct hashtable_item*)malloc(max *sizeof(struct hashtable_item*));


init_array();
do{
printf("Implementation of Hash Table in C with Linear Probing \n\n");
printf("MENU-: \n1.Inserting item in the Hashtable"
"\n2.Removing item from the Hashtable"
"\n3.Check the size of Hashtable"
"\n4.Display Hashtable"
"\n\n Please enter your choice-:");

scanf("%d",&choice);

switch(choice)
{

case1:
printf("Inserting element in Hashtable\n");
printf("Enter key and value-:\t");
scanf("%d %d",&key,&value);
insert(key, value);
break;

case2:
printf("Deleting in Hashtable \n Enter the key to delete-:");
scanf("%d",&key);
remove_element(key);
break;

case3:
n = size_of_hashtable();
printf("Size of Hashtable is-:%d\n", n);
break;

case4:
display();
break;
default:
printf("Wrong Input\n");
}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d",&c);

}while(c ==1);

getch();
}
OUTPUT

Implementation of Hash Table in C


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 3


Size of Hash Table is-: 0

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C
MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 1


Inserting element in Hash Table
Enter key -: 1

key (1) and value (1) has been inserted

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C chaining with singly linked list
MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 4


array[0] has no elements
array[1] has no elements key = 1 and value = 1
array[2] has no elements
array[3] has no elements
array[4] has no elements
array[5] has no elements
array[6] has no elements
array[7] has no elements
array[8] has no elements
array[9] has no elements
*****************************
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C
MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 2


Deleting key from Hash Table
Enter the key to delete-: 3

This key does not exist.

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C
MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 2


Deleting key from Hash Table
Enter the key to delete-: 1

Key 1 has been removed.

Do you want to continue-:(press 1 for yes) 2

Result:
Thus the C program to implement hash table is executed successfully and output
is verified.
PROGRAM TO IMPLEMENT MULTIPLE STACK IN A
Ex.No:CBS1 SINGLE ARRAY USING C LANGUAGE

DATE
Aim:
To write a C program to implement multiple stack in a single array.

Algorithm:
1. Create an array and define the MAX
2. Initialize MAX, TopA, TopB.
3. Call Insert option and check whether the stack is full or not if not full insert
the item to the stack
4. Call delete option and check whether the stack is empty or not and not empty
delete the item from stack and place it to another stack.
5. Perform all the operations
6. Stop the program
PROGRAM:

#include<stdio.h>
#include<conio.h>
#define MAX_X 5
#define MAX_Y 5
int topx=-1;
int topy=10;
/*Begin of push_x*/
void push_x(int *stack)
{
int info;

if(topx>=(MAX_X-1))
{ printf("\n\nStack OverFlow");
return;
}
else
{ printf("\n\nEnter The info To Push");
scanf("%d",&info);
topx++;
stack[topx]=info;
}}
/*End of push_x*/
/*Begin of push_y*/
void push_y(int *stack)
{
int info;

if(topy<=(MAX_Y))
{
printf("\n\nStack OverFlow");
return;
}
else
{
printf("\n\nEnter The info To Push");
scanf("%d",&info);
topy--;
stack[topy]=info;
}
}
/*End of push_y*/
/*Begin of pop_x*/
void pop_x(int *stack)
{ if(topx==-1)
{
printf("Stack X is Underflow");
return;
}
else
{
printf("Item Poped from stack X is:%d\n",stack[topx]);

topx--;
}
}
/*End of pop_x*/
/*Begin of pop_y*/
void pop_y(int *stack)
{ if(topy==10)
{printf("Stack y is Underflow");
return;
}
else
{ printf("Item Poped from stack Y is:%d\n",stack[topy]);
topy++;
}}
/*End of pop_y*/
/*Begin of display_x*/
void display_x(int *stack)
{
int i;
if(topx==-1)
{
printf("Stack X is Empty");
return;
}
else
{ for(i=topx;i>=0;i--)
{printf("%d,",stack[i]);}
printf("\n");
}}
/*End of display_x*/
/*Begin of display_y*/
void display_y(int *stack)
{
int i;
if(topy==10)
{printf("Stack Y is Empty");
return;}
else
{for(i=topy;i<=9;i++)
{
printf("%d,",stack[i]);
}
printf("\n");
} }
/*End of display_y*/
/*Begin of main*/
main()
{ int choice;
char ch;
int stack[MAX_X+MAX_Y];
do
{ printf("1.Push_X\n2.Push_Y\n");

printf("\n3.Pop_X\n4.Pop_Y\n");
printf("\n5.Display_X\n6.Display_Y\n");
printf("\n7.Exit");
printf("\n\nEnter Choice");
scanf("%d",&choice);
switch(choice)
{
case 1: push_x(stack);break;
case 2: push_y(stack);break;

case 3: pop_x(stack);break;
case 4: pop_y(stack);break;

case 5: display_x(stack);break;
case 6: display_y(stack);break;
case 7: break;
default: printf("Wrong Option...");
}
}while(choice!=7);
}
/*End of main*/
OUTPUT:

Result:
Thus the C programs to implement multiple stacks are executed successfully and
output is verified.
Ex.No:CBS2 PROGRAM TO IMPLEMENT EXPRESSION TREE

DATE

Aim:
To write a C program to implement expression tree using stacks and find its inorder,
preorder and postorder traversals.
Algorithm:
1. Declare the structure of the node
2. Now create an expression tree by using stack operations and initialize the
stack is empty. Insert the element and increment the top position.
3. Create the expression tree and do the operations of trees (infix, prefix, postfix)
4. Perform all the operations
5. Stop the program
PROGRAM:

#include<STDIO.H>
#include<CONIO.H>
#include<MALLOC.H>
typedef struct tree
{
char data;
struct tree *left;
struct tree *right;
}*pos;
pos stack[30];
int top=-1;
pos newnode(char b)
{
pos temp;
temp=(struct tree*)malloc(sizeof(struct tree));
temp->data=b;
temp->left=NULL;
temp->right=NULL;
return(temp);
}
void push(pos temp)
{
stack[++top]=temp;
}
pos pop()
{
pos p;
p=stack[top--];
return(p);
}
void inorder(pos t)
{

if(t!=NULL)
{
inorder(t->left);
printf(“%s”,t->data);
inorder(t->right);
}
}
void preorder(pos t)
{
if(t!=NULL)
{
printf(“%s”,t->data);
preorder(t->left);
inorder(t->right);

}
}
void postorder(pos t)
{if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
printf(“%s”,t->data);
}
}
void main()
{
char a[20];pos temp,t;int j,i;
clrscr();
printf(“\nEnter the postfix expression”);
gets(a);
for(i=0;a[i]!=NULL;i++)
{
if(a[i]==’*’ || a[i]==’/’ || a[i]==’+’ || a[i]==’-')
{
temp=newnode(a[i]);
temp->right=pop();
temp->left=pop();
push(temp);
}
else
{
temp=newnode(a[i]);
push(temp);
}
}
inorder(temp);
printf(“\n”);
preorder(temp);
printf(“\n”);
postorder(temp);
getch();
}

OUTPUT:

Inorder traversal
5 ->12 ->6 ->1 ->9 ->
Preorder traversal
1 ->12 ->5 ->6 ->9 ->
Postorder traversal
5 ->6 ->12 ->9 ->1 ->

Result:
Thus the C programs to implement expression tree is executed successfully and
output is verified.
Ex.No:CBS3 PROGRAM TO IMPLEMENT TOPOLOGICAL SORT USING
ARRAYS

DATE
Aim:
To write a C program to implement topological sort using arrays

Algorithm:
1. Declare the size of the array
2. Now apply the various operations on topological sorting.
3. A queue application is followed in this sorting and indegree=0 and find the
adjacency nodes having indegree 0 and delete from the queue.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop the program
PROGRAM:

#include <stdio.h>
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++){
indeg[i]=0;
flag[i]=0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0)){
printf("%d ",(k+1));
flag [k]=1;
}
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}

OUTPUT:

Enter the no of vertices:


4
Enter the adjacency matrix:
Enter row 1
0110
Enter row 2
0001
Enter row 3
0001
Enter row 4
0000
The topological order is:1 2 3 4

Result:
Thus the C programs to implement topological sorting for a graph is executed
successfully and output is verified.

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