Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
85 views99 pages

Dsa Lab Manual

The document contains a lab manual for the third semester B.Tech computer science course at Jaipur National University. It includes 12 experiments covering topics like array and linked list implementation of stacks, queues, binary trees, sorting algorithms, and more. It provides the objectives, algorithms, programs, sample outputs and viva questions for each experiment. It also lists the hardware and software available in the lab for 30 students, including standalone desktops and C/C++ programming tools.

Uploaded by

RACHANA YADAV
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)
85 views99 pages

Dsa Lab Manual

The document contains a lab manual for the third semester B.Tech computer science course at Jaipur National University. It includes 12 experiments covering topics like array and linked list implementation of stacks, queues, binary trees, sorting algorithms, and more. It provides the objectives, algorithms, programs, sample outputs and viva questions for each experiment. It also lists the hardware and software available in the lab for 30 students, including standalone desktops and C/C++ programming tools.

Uploaded by

RACHANA YADAV
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/ 99

JAIPUR NATIONAL UNIVERSITY

DEPARTMENT OF COMPUTER SCIENCE

ACADEMIC YEAR: 2021-2022

ODD SEMESTER

LAB MANUAL

THIRD SEMSTER
B.Tech - CSE

Prepared By

Ms. RACHANA YADAV


ASSISTANT PROFESSO

1
INDEX
NO EXPERIMENT NAME
A Introduction/ Description of major Software & Hardware involved in lab
1.1 Array Implementation of List ADTs
1.2 Linked List Implementation of List ADTs
2.1 Array Implementation of Stack ADTs
2.2 Linked List Implementation of Stack ADTs
3.1 Array Implementation of Queue ADTs
3.2 Linked List Implementation of Queue ADTs
4.1 Applications of List : Polynomial Manipulation
4.2 Applications of Stack: Infix To Postfix Expression
5 Implementation of Binary trees And operations of Binary trees
6 Implementation of Binary Search Trees
7 Implementation of AVL Trees
8.1 Linear Search
8.2 Binary Search
8.3 Bubble Sort
8.4 Insertion Sort
- TOPIC BEYOND THE SYLLABUS “ Implementation of Doubly Linked
List”

2
LIST OF EQUIPMENTS FOR A BATCH OF 30 STUDENTS

HARDWARE

Standalone desktops 30 Nos

SOFTWARE

C / C++ / Turbo C / Equivalent Software

C programming is a general-purpose, procedural, imperative computer programming language


developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating
system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity
along with Java programming language, which is also equally popular and most widely used among modern
software programmers.

The UNIX OS was totally written in C.


Today C is the most widely used and popular System Programming Language.
Most of the state-of-the-art software have been implemented using C.
Today's most popular Linux OS and RDBMS MySQL have been written in C.

C++
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell
Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
This C++ tutorial adopts a simple and practical approach to describe the concepts of C++ for beginners to advanced
software engineers.

Turbo C
Turbo C was an integrated development environment (IDE) for programming in the C language. It was developed
by Borland and first introduced in 1987. At the time, Turbo C was known for its compact size, comprehensive manual,
fast compile speed and low price.

3
Ex.No:1.1 ARRAY IMPLEMENTATION OF LIST ADTs

AIM

To write a C program to implement list using an array

PRE LAB DISCUSSION

Array of list is an important data structure used in many applications. It is an interesting


structure to form a useful data structure. It combines static and dynamic structure. Static means
array and dynamic means linked list used to form a useful data structure. Array elements can be
stored in consecutive manner in memory. Insert and delete operation takes more time in array.
Array elements cannot be added, deleted once it is declared. In array, elements can be modified
easily by identifying the index value. Pointer cannot be used in array. So, it does not require extra
space in memory forpointer.

ALGORITHM

Step 1: Start.
Step 2: Declare the necessary functions for implementation.
Step 3: Get the input from the user and store it an array.
Step 4: In Insertion, half of the elements to be shifted upwards and in deletion half of the
elements to be shifted downwards.
Step 5: Display the output using an array.
Step 6: Stop.

PROGRAM

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

4
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 correctchoice:");
}
printf("\n Do u want tocontinue:::");

5
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++)

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

7
OUTPUT
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice1
Enter the number of nodes 2
Enter theElement:2
Enter theElement:3
Do u want to continue:::y
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice 5
The Elements of The list ADT are:
2
3
Do u want to continue:::y
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

8
Enter your Choice 4
Enter the position u need to insert::0
Enter the element to inert::5
The list after insertion::
The Elements of the list ADT are:
5
2
3
Do u want to continue:::y
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice 2
Enter the position u want to delete::1
The Elements after deletion
5
3
Do u want to continue:::

VIVA (PRE & POST LAB) QUESTIONS

1. How to delete an element using array inlist?


2. How to insert an element using array inlist?
3. Which data structure refers to linear collection of dataitems.
4. How to search an element inlist?
5. What happens when there is no space left in free storagelist?
RESULT

Thus the C program to implement list using array was completed successfully.

9
Ex.No: 1.2 LINKED LIST IMPLEMENTATION OF LIST ADTS

AIM

To write a C program to implement singly linked list.

PRE LAB DISCUSSION

Linked list is a linear data structure. It is a collection of data elements, called nodes
pointing to the next node by means of a pointer. In linked list, each node consists of its own data
and the address of the next node and forms a chain.

Linked list contains a link element called first and each link carries a data item. Entry point intothe
linked list is called the head of the list. Link field is called next and each link is linked with its next
link. Last link carries a link to null to mark the end of thelist.
Linked list is a dynamic data structure. While accessing a particular item, start at the head and
follow the references until you get that data item.

Linked list is used while dealing with an unknown number of objects:

Linked list contains two fields - First field contains value and second field contains a link to the
next node. The last node signifies the end of the list that means NULL.
The real life example of Linked List is that of Railway Carriage. It starts from engine and then
the coaches follow. Coaches can traverse from one coach to other, if they connected to each
other.

10
ALGORITHM
Step 1: Start
Step 2: Creation: Get the number of elements, and create the nodes having structures
DATA,LINK and store the element in Data field, link them together to form a
linked list.
Step 3: Insertion: Get the number to be inserted and create a new node store the value in
DATA field. And insert the node in the required position.
Step 4: Deletion: Get the number to be deleted. Search the list from the beginning and
locate the node then delete the node.
Step 5: Display: Display all the nodes in the list.
Step 6: Stop.
PROGRAM

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0

typedef struct list


{
int no;
struct list *next;
}LIST;
LIST *p,*t,*h,*y,*ptr,*pt;

void create( void );


void insert( void );
void delet( void );
void display ( void );
int j,pos,k=1,count;

void main()

11
{
int n,i=1,opt;
clrscr();
p = NULL;
printf("%d",sizeof(LIST));
printf( "Enter the no of nodes :\n " );
scanf( "%d",&n );
count = n;
while( i <= n)
{
create();
i++;
}
printf("\nEnter your option:\n");
printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n");
do
{
scanf("%d",&opt);
switch( opt )
{
case 1:
insert();
count++;
break;
case 2:
delet();
count--;
if ( count == 0 )
{
printf("\n List is empty\n");
}
break;

case 3:
printf("List elements are:\n");
display();
break;
}
printf("\nEnter your option \n");
}while( opt != 4 );
getch();
}

void create ( )
{
if( p== NULL )

12
{
p = ( LIST * ) malloc ( sizeof ( LIST ) );
printf( "Enter the element:\n" );
scanf( "%d",&p->no );
p->next = NULL;
h = p;
}
else
{
t= ( LIST * ) malloc (sizeof( LIST ));
printf( "\nEnter the element" );
scanf( "%d",&t->no );
t->next = NULL;
p->next = t;
p = t;
}
}

void insert()
{
t=h;
p = ( LIST * ) malloc ( sizeof(LIST) );
printf("Enter the element to be inserted:\n");
scanf("%d",&p->no);
printf("Enter the position to insert:\n");
scanf( "%d",&pos );
if( pos == 1 )
{
h = p;
h->next = t;
}
else
{
for(j=1;j<(pos-1);j++)
t = t->next;
p->next = t->next;
t->next = p;
t=p;
}
}

void delet(){
printf("Enter the position to delete:\n");
scanf( "%d",&pos );
if( pos == 1 )
{

13
h = h->next ;
}
else
{
t=h;
for(j=1;j<(pos-1);j++)
t = t->next;
pt=t->next->next;
free(t->next);
t->next= pt;
}
}

void display()
{
t= h;
while( t->next != NULL )
{
printf("\t%d",t->no);
t = t->next;
}
printf( "\t %d\t",t->no );
}

OUTPUT

Enter the no of nodes: 3


Enter the element: 1
Enter the element 2
Enter the element 3
Enter your option:
1. Insert 2.Delete 3.Display 4.Exit
3
List elements are:
123
Enter your option 1
Enter the element to be inserted:
12
Enter the position to insert: 1
Enter your option 3
List elements are:
12 1 2 3
Enter your option 1
Enter the element to be inserted:
13
Enter the position to insert: 3

14
Enter your option 1
Enter the element to be inserted:
14
Enter the position to insert:6
Enter your option 3
List elements are:
12 1 13 2 3 14
Enter your option2
Enter the position todelete:1
Enter your option3
List elements are:
1 13 2 3 14
Enter your option2
Enter the position todelete:3
Enter your option3
List elements are:
1 13 3 14
Enter your option2
Enter the position todelete:4
Enter your option3
List elements are:
1 13 3
Enter your option:6

VIVA (PRE & POST LAB) QUESTIONS

1. How many modifications are required to delete a node at the beginning?


2 How many modifications are required to insert a node in the middle of the linked list?
3.Which node contains NULL pointer in a single linked list?
4.Which node points to the first node in list?
5.How does array differ from linked list?

RESULT

Thus the C program to implement List was completed successfully.

15
Ex. No: 2.1 ARRAY IMPLEMENTATION OF STACK ADTs

AIM

To write a C program to implement Stack operations such as push, pop and display using array.

PRE LAB DISCUSSION

An array is a random access data structure, where each element can be accessed directly
and in constant time. A typical illustration of random access is a book - each page of the book can
be open independently of others. Random access is critical to many algorithms, for example
binarysearch.

A stack data structure can be implemented using one dimensional array. But stack
implemented using array, can store only fixed number of data values. This implementation is very
simple, just define a one dimensional array of specific size and insert or delete the values into that
array by using LIFO principle with the help of a variable 'top'. Initially top is set to -1. Whenever
we want to insert a value into the stack, increment the top value by one and then insert. Whenever
we want to delete a value from the stack, then delete the top value and decrement the top value by
one.

ALGORITHM

Step 1: Start.
16
Step 2: Initialize top = -1;
Step 3: Push operation increases top by one and writes pushed element to storage[top];
Step 4: Pop operation checks that top is not equal to -1 and decreases top variable by 1;
Step 5: Display operation checks that top is not equal to -1 and returns storage[top];
Step 6: Stop.

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<process.h>
#define size 5
int item;
int s[10];
int top;
void display()
{
int i;
if(top==-1)
{
printf("\nstack is empty");
return;
}
printf("\nContent of stack is:\n");
for(i=0;i<=top;i++)
printf("%d\t",s[i]);
}
void push()
{

17
if(top==size-1)
{
printf("\nStack is full");
return;
}
printf("\nEnter item:\n");
scanf("%d",&item);
s[++top]=item;
}
void pop()
{
if(top==-1)
{
printf("\nstack is empty");
return;
}
printf("\nDeleted item is: %d",s[top]);
top--;
}
void main()
{
int ch;
top=-1;
clrscr();
printf("\n1.push\t\t2.pop\n3.display\t4.exit\n");
do{
printf("\nEnter your choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1:// printf("Enter item:\n");

18
//scanf("%d",&item);
push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong entry ! try again");
}
}while(ch<=4);
getch();
}

OUTPUT
1.push 2.pop
3.display 4.exit
Enter your choice:
1
Enter item:
100
Enter your choice:
1
Enter item:
200
Enter your choice:
1
Enter item:
300
Enter your choice:
2

19
Deleted item is: 300
Enter your choice:
3

Content of stack is:


100 200
Enter yourchoice:4

VIVA (PRE & POST LAB) QUESTIONS

1.How to remove an element from stack?


2.How to insert an element into a stack?
3.Is it possible to store any number of data elements in stack?
4.What are the demerits of stack?
5. What happens when you pop from an empty stack while implementing using the Stack
ADT ?

RESULT

Thus the C program to implement stack using array was executed successfully.

20
Ex. No: 2.2 LINKED LIST IMPLEMENTATION OF STACK

AIM

To write a C program to implement Stack operations such as push, pop and display using
linked list.

PRE LAB DISCUSSION

The major problem with the stack implemented using array is, it works only for fixed
number of data values. That means the amount of data must be specified at the beginning of the
implementation itself. Stack implemented using array is not suitable, when we don't know the size
of data which we are going to use. A stack data structure can be implemented by using linked list
data structure. The stack implemented using linked list can work for unlimited number of values.
That means, stack implemented using linked list works for variable size of data. So, there is no
need to fix the size at the beginning of the implementation. The Stack implemented using linked
list can organize as many data values as wewant.
In linked list implementation of a stack, every new element is inserted as 'top' element.
That means every newly inserted element is pointed by 'top'. Whenever we want to remove an
element from the stack, simply remove the node which is pointed by 'top' by moving 'top' to its
next node in the list. The next field of the first element must be always NULL.

Example

In above example, the last inserted node is 99 and the first inserted node is 25. The order of
elements inserted is 25, 32,50 and 99.

21
There are two basic operations performed in a Stack:
1. Push():is used to add or insert new elements into thestack.
2. Pop():is used to delete or remove an element from thestack.

ALGORITHM

Step 1: Start.
Step 2: push operation inserts an element at the front.
Step 4: pop operation deletes an element at the front of the list;
Step 5: display operation displays all the elements in the list.
Step 6: Stop.
PROGRAM

#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
void pop();
void push(int value);
void display();
struct node
{
int data;
struct node *link;
};
struct node *top=NULL,*temp;

22
void main()
{
int choice,data;
while(1) //infinite loop is used to insert/delete infinite number of elements in stack
{
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("\nEnter ur choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: //To push a new element into stack
printf("Enter a new element :");
scanf("%d",&data);
push(data);
break;
case 2: // pop the element from stack
pop();
break;
case 3: // Display the stack elements
display();
break;
case 4: // To exit
exit(0);
}
}
getch();
//return 0;
}
void display()
{
temp=top;

23
if(temp==NULL)
{
printf("\nStack is empty\n");
}
printf("\n The Contents of the Stackare...");
while(temp!=NULL)
{
printf(" %d->",temp->data);
temp=temp->link;
}
}
void push(int data)
{
temp=(struct node *)malloc(sizeof(struct node)); // creating a space for thenew
element.
temp->data=data;
temp->link=top;
top=temp;
display();
}
void pop()
{
if(top!=NULL)
{
printf("The poped element is %d",top->data);
top=top->link;
}
else
{
printf("\nStack Underflow");
}

24
display();
}

OUTPUT

1. Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :10
The Contents of the Stack are... 10 ->

1. Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :20
The Contents of the Stack are... 20 -> 10 ->
1.Push
2. Pop
3.Display
4.Exit

Enter ur choice:1
Enter a new element :30
The Contents of the Stack are... 30 -> 20 -> 10 ->
1.Push
2.Pop
3.Display
4.Exit

25
Enter ur choice:2
The poped element is 30
The Contents of the Stack are... 20 -> 10 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
The Contents of the Stack are... 20 -> 10 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:4

VIVA (PRE & POST LAB) QUESTIONS

1. How an element can be pushed and popped intostack?


2. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a
time, what is the order ofremoval?
3. What is the top ofstack?
4. How to represent stack using linkedlist?
5. What is structure of stack?

RESULT

Thus the C program to implement Stack using linked list was completed successfully.

26
Ex. No: 3.1 ARRAY IMPLEMENTATION OF QUEUE ADTS

AIM

To write a C program to implement Queue operations such as enqueue, dequeue and


display using array.

PRE LAB DISCUSSION

Queue implemented using array can store only fixed number of data values. The
implementation of queue data structure using array is very simple, just define a one dimensional
array of specific size and insert or delete the values into that array by using FIFO (First In First
Out) principle with the help of variables 'front'and 'rear'. Initially both 'front' and 'rear' are set to
-1. Whenever, we want to insert a new value into the queue, increment 'rear' value by one and then
insert at that position. Whenever we want to delete a value from the queue, then increment 'front'
value by one and then display the value at 'front' position as deleted element.

The Front and Rear of the queue point at the first index of the array. (Array index starts
from0).
While adding an element into the queue, the Rear keeps on moving ahead and always
points to the position where the next element will be inserted. Front remains at the first
index.

27
ALGORITHM
Step 1: Start.
Step 2: Initialize front=0; rear=-1.
Step 3: Enqueue operation moves a rear by one position and inserts a element at the rear.
Step 4: Dequeue operation deletes a element at the front of the list and moves the front by
one Position.
Step 5: Display operation displays all the element in the list.
Step 6: Stop.
PROGRAM
#include<stdio.h>
#include<conio.h>
#defineSIZE5 /* Size of Queue*/
intQ[SIZE],f=0,r=-1; /* Global declarations*/
Qinsert(int elem)
{ /* Function for Insert operation*/
if(Qfull())
printf("\n\n Overflow!!!!\n\n");
else
{
++r;
Q[r]=elem;
}
}

28
int Qdelete()
{ /* Function for Delete operation*/
int elem;
if(Qempty()){ printf("\n\nUnderflow!!!!\n\n");
return(-1); }
else
{
elem=Q[f];
f=f+1;
return(elem);
}
}

int Qfull()
{ /* Function to Check Queue Full*/
if(r==SIZE-1) return1;
return 0;
}

int Qempty()
{ /* Function to Check Queue Empty*/
if(f > r) return1;
return 0;
}

display()
{ /* Function to display status of Queue*/
inti;
if(Qempty()) printf(" \n Empty Queue\n");
else

29
{
printf("Front->");
for(i=f;i<=r;i++)
printf("%d ",Q[i]);
printf("<-Rear");
}
}

void main()
{ /* Main Program */
int opn,elem;
do
{
clrscr();
printf("\n ### Queue Operations using Arrays### \n\n");
printf("\n Press 1-Insert, 2-Delete,3-Display,4-Exit\n");
printf("\n Your option ? ");
scanf("%d",&opn);
switch(opn)
{
case 1: printf("\n\nRead the element to be Inserted ?");
scanf("%d",&elem);
Qinsert(elem); break;
case 2: elem=Qdelete();
if( elem != -1)
printf("\n\nDeleted Element is %d \n",elem);
break;
case 3: printf("\n\nStatus of Queue\n\n");
display(); break;
case 4: printf("\n\n Terminating \n\n"); break;
default: printf("\n\nInvalid Option !!! Try Again !! \n\n");

30
break;
}
printf("\n\n\n\n Press a Key to Continue . . . ");
getch();
}while(opn != 4);
getch();
}

OUTPUT

### Queue Operations using Arrays###


Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 1
Read the element to be Inserted ?100
Press a Key to Continue . . .
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 1
Read the element to be Inserted ?200
Press a Key to Continue . . .
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 1
Read the element to be Inserted ?300
Press a Key to Continue . . .
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 2
Deleted Element is 100
Press a Key to Continue . . .

### Queue Operations using Arrays###

31
Press 1-Insert,2-Delete,3-Display,4-Exit
Your option ?3
Status ofQueue
Front->200 300 <-Rear
Press a Key to Continue . ..

VIVA (PRE & POST LAB) QUESTIONS

1. If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted one at a
time, in what order will they beremoved?
2. When does a normal queue gets full if implemented using an array of sizeMAX_SIZE
3. What is the term for inserting into a full queue known as?
4.What is the advantage of circular queue over linear queue?
5.How to check an emptyqueue?

RESULT
Thus the C program to implement Queue using array was completed successfully.

32
Ex. No: 3.2 LINKED LIST IMPLEMENTATION OF QUEUE

AIM

To write a C program to implement Queue operations such as enqueue, dequeue and


display using linked list.

PRE LAB DISCUSSION

The major problem with the queue implemented using array is, It will work for only fixed
number of data. That means the amount of data must be specified in the beginning itself. Queue
using array is not suitable when we don't know the size of data which we are going to use. A queue
data structure can be implemented using linked list data structure. The queue which is implemented
using linked list can work for unlimited number of values. That means, queue using linked list can
work for variable size of data (No need to fix the size at beginning of the implementation). The
Queue implemented using linked list can organize as many data values as we want. In linked list
implementation of a queue, the last inserted node is always pointed by 'rear' and the first node is
always pointed by 'front'.

Example

In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted
node is 10 and it is pointed by 'front'. The order of elements inserted is 10, 15, 22 and 50.

There are two basic operations performed on a Queue.


Enqueue():This function defines the operation for adding an element into queue. Dequeue():This
function defines the operation for removing an element from queue.

ALGORITHM

Step 1: Start.
Step 2: Enqueue operation inserts an element at the rear of the list.
Step 4: Dequeue operation deletes an element at the front of the list.
Step 5: Display operation display all the element in the list.
Step 6: Stop.
33
PROGRAM

#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;

void insert(int);
void delete();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);

34
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{

35
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}

36
OUTPUT

37
VIVA (PRE & POST LAB) QUESTIONS

1. What is structure ofqueue?


2. How an element can be inserted and deleted fromqueue?
3. How to represent queue using linkedlist?
4. In linked list implementation of a queue, where does a new element beinserted?
5. In linked list implementation of a queue, from where is the itemdeleted?

RESULT

Thus the C program to implement Queue using linked list was completed successfully.

38
Ex.No:4.1 APPLICATIONS OF LIST

AIM

To write a ‘C’ program to represent a polynomial as a linked list and write functions for
polynomial addition

PRE LAB DISCUSSION

A polynomial equation is an equation that can be written in the form. axn + bxn-1 + . . . +
rx+ s = 0, where a, b, . . . , r and s are constants. We call the largest exponent of x appearing in a
nonzero term of a polynomial the degree of that polynomial.A Polynomial has mainly two fields
Exponent and coefficient.

Node of a Polynomial:

For example 3x^2 + 5x + 7 will represent as follows.

In each node the exponent field will store the corresponding exponent and the coefficient field
will store the corresponding coefficient. Link field points to the next item in the
polynomial.Given two polynomial numbers represented by a linked list. Write a function that
add these lists means add the coefficients which have same variable powers.

Example:
Input:
1st number = 5x^2 + 4x^1 + 2x^0
2nd number = 5x^1 + 5x^0
Output:
5x^2 + 9x^1 + 7x^0

39
ALGORITHM

Step1:Start the program


Step2:Get the coefficients and powers for the two polynomials to be added.
Step3:Add the coefficients of the respective powers.
Step4:Display the added polynomial.
Step5:Terminate the program.
PROGRAM

#include<stdio.h>
#include<conio.h>
struct polynomial
{
int coff;
int pow;
struct polynomial *link;
}*ptr,*start1,*node,*start2,*start3,*ptr1,*ptr2;
typedef struct polynomial pnl;
int temp1,temp2;

void main()
{
void create(void);
void prnt(void);
void suml(void);
void sort(void);
clrscr();
printf("Enrter the elements of the first polynomial :");
node = (pnl *) malloc(sizeof (pnl));
start1=node;
if (start1==NULL)
{
printf(" Unable to create memory.");
getch();
exit();
}
create();
printf("Enter the elements of the second poly :");
node = (pnl *) malloc(sizeof (pnl));

40
start2=node;
if (start2==NULL)
{
printf("Unable to create memory.");
getch();
exit();
}
create();
clrscr();
//printing the elements of the lists
printf("The elements of the poly first are :");
ptr=start1;
prnt();
printf("The elements of the poly second are :");
ptr=start2;
prnt();
printf("The first sorted list is :");
ptr=start1;
sort();
ptr=start1;
prnt();
printf("The second sorted list is :");
ptr=start2;
sort();
ptr=start2;
prnt();
printf("The sum of the two lists are :");
suml();
ptr=start3;
prnt();
getch();
}
/* */
voidcreate()
{
char ch;
while(1)
{
printf(" Enter the coff and pow :");
scanf("%d%d",&node->coff,&node->pow);
if (node->pow==0 )
{
ptr=node;
node=(pnl *)malloc(sizeof(pnl));
node=NULL;
ptr->link=node;

41
break;
}
printf("Do u want enter more coff ?(y/n)");
fflush(stdin);
scanf("%c",&ch);
if (ch=='n' )
{
ptr=node;
node=(pnl *)malloc(sizeof(pnl));
node=NULL;
ptr->link=node;
break;
}
ptr=node;
node=(pnl *)malloc(sizeof(pnl));
ptr->link=node;
}
}
/* */
voidprnt()
{
int i=1;
while(ptr!=NULL )
{
if(i!=1)
printf("+ ");
printf(" %dx^%d\n ",ptr->coff,ptr->pow);
ptr=ptr->link;
i++;
}
//printf(" %d^%d",ptr->coff,ptr->pow);
}
/* */
voidsort()
{
for(;ptr->coff!=NULL;ptr=ptr->link)
for(ptr2=ptr->link;ptr2->coff!=NULL;ptr2=ptr2->link)
{
if(ptr->pow>ptr2->pow)
{
temp1=ptr->coff;
temp2=ptr->pow;
ptr->coff=ptr2->coff;
ptr->pow=ptr2->pow;
ptr2->coff=temp1;
ptr2->pow=temp2;

42
}
}
}
/* */
voidsuml()
{
node=(pnl *)malloc (sizeof(pnl));
start3=node;

ptr1=start1;
ptr2=start2;

while(ptr1!=NULL && ptr2!=NULL)


{
ptr=node;
if (ptr1->pow > ptr2->pow )
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B
}
else if ( ptr1->pow < ptr2->pow )
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list A
}
else
{
node->coff=ptr2->coff+ptr1->coff;
node->pow=ptr2->pow;
ptr1=ptr1->link; //update ptr list A
ptr2=ptr2->link; //update ptr listB
}

node=(pnl *)malloc (sizeof(pnl));


ptr->link=node; //update ptr listC
}//end of while

if(ptr1==NULL) //end of listA


{
while(ptr2!=NULL)
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B

43
ptr=node;
node=(pnl *)malloc (sizeof(pnl));
ptr->link=node; //update ptr list C
}
}
elseif(ptr2==NULL) //end of listB
{
while(ptr1!=NULL)
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list B
ptr=node;
node=(pnl *)malloc (sizeof(pnl));
ptr->link=node; //update ptr list C
}
}
node=NULL;
ptr->link=node;
}
OUTPUT

Enter the elements of the first polynomial : Enter the coff and pow :1 1
Do u want enter more coff ?(y/n)y
Enter the coff and pow :1 0
Enter the elements of the second poly : Enter the coff and pow :1 1
Do u want enter more coff ?(y/n)y
Enter the coff and pow :2 0
The elements of the poly first are : 1x^1 + 1x^0
The elements of the poly second are : 1x^1 + 2x^0
The first sorted list is : 1x^0 +1x^1
The second sorted list is : 2x^0 + 1x^1
The sum of the two lists are : 3x^0 +2x^1

VIVA (PRE & POST LAB) QUESTIONS

1. Give the linked representation of the following polynomial: 7x3y2 – 8x2y + 3xy + 11x – 4
2.Which data structure is suited for polynomial manipulation. Givereason.
3.How to add two polynomial using linked list.
4.Specify the need for malloc() function.
5. Mention the structure of polynomial node.

RESULT

Thus the C program to implement Polynomial using linked list was completed successfully.

44
Ex.No:4.2 APPLICATIONS OF STACK

AIM

To write a C program to implement the conversion of infix to postfix expression using


Stack.

PRE LAB DISCUSSION

One of the applications of Stack is in the conversion of arithmetic expressions in high-


level programming languages into machine readable form. An arithmetic expression may consist
of more than one operator and two operands e.g. (A+B)*C(D/(J+D)).These complex arithmetic
operations can be converted into polish notation using stacks which then can be executed in two
operands and an operator form.
Infix Expression:
Itfollows the scheme of <operand><operator><operand>i.e. an <operator> is preceded
and succeeded by an <operand>. Such an expression is termed infix expression. E.g.,A+B
Postfix Expression:
It follows the scheme of <operand><operand><operator>i.e. an <operator> is succeeded by
both the <operand>. E.g., AB+
Steps to convert Infix To Postfix
Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression Y.
1. Push “(“onto Stack, and add “)” to the end ofX.
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 toY.
4. If a left parenthesis is encountered, push it ontoStack.
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 thanoperator.
2. Add operator toStack.
[End ofIf]
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 isencountered.
2. Remove the leftParenthesis.
[End ofIf]
[End of If]
7. END.

45
ALGORITHM

Step 1: Start.
Step 2: Create a stack to store operand andoperator.
Step 3: In Postfix notation the operator follows the two operands and in the infix notation
the operator is in between the twooperands.
Step 4: Consider the sum of A and B. Apply the operator “+” to the operands A and B
and write the sum as A+B is INFIX. + AB is PREFIX. AB+ isPOSTFIX
Step 5: Get an Infix Expression as input and evaluate it by first converting it to postfix and
then evaluating the postfix expression.
Step 6: The expressions with in innermost parenthesis must first be converted to postfix so
that they can be treated as single operands. In this way Parentheses can be
successively eliminated until the entire expression isconverted.
Step 7: The last pair of parentheses to be opened with in a group of parentheses encloses
the first expression with in that group to be transformed. This last-in first-out
immediately suggests the use of Stack. Precedence plays an important role in the
transforming infix to postfix.
Step 8: Stop.

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20
int top=-1;

46
char pop();
char stack[MAX];
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 '(':

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

48
j++;
}
push(symbol);
}//end ofelse.
}//end ofelse.
}//end ofelse.
}//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];

49
top--;
return a;
}

OUTPUT

Enter the valid infix string:


(a+b)*c
The corresponding postfix string is:
ab+c*

VIVA (PRE & POST LAB) QUESTIONS

1. What is the output of the following expression: 2 3 4 5 + *-


2. What is the maximum difference between number of operators andoperands?
3. What is the advantage of postfixexpression?
4. Which expression doesn’t requireparenthesis?
5. What is the output of the following expression: + * - 2 3 45

RESULT

Thus the C program to convert infix to postfix expression using Stack was completed
successfully.

50
Ex.No:5 IMPLEMENTATION OF BINARY TREES AND OPERATIONS OF BINARY TREES

AIM

To write a C program to implement the binary trees and its operations.

PRE LAB DISCUSSION

A binary tree is a tree data structure in which each node has at most two children, which
are referred to as the left child and the right child.

Insertion:
In binary trees, a new node before insert has to specify 1) whose child it is going to be 2)
mention whether new node goes as left/right child. For example(below image),

To add a new node to leaf node, a new node should also mention whether new node goes as
left/right child.

51
Deletion:
For deletion, only certain nodes in a binary tree can be removed unambiguously.
Suppose that the node to delete is node A. If A has no children, deletion is accomplished by setting
the child of A's parent to null. If A has one child, set the parent of A's child to A's parent and set
the child of A's parent to A's child. In a binary tree, a node with two children cannot be deleted
unambiguously.

ALGORITHM

Step 1: Start.
Step 2: Create a Binary Tree for N elements.
Step 3: Insert an element in binary tree
Step 4: Traverse the tree in inorder.
Step 5: Traverse the tree in preorder
Step 6: Traverse the tree in postorder.
Step 7: Stop

PROGRAM

#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *rlink;
struct node *llink;
}*tmp=NULL;
typedef struct node NODE;
NODE *create();
void preorder(NODE *);
void inorder(NODE *);

52
void postorder(NODE *);
void insert(NODE *);
void main()
{
int n,i,m;
clrscr();
do
{
printf(“\n\n0.create\n\n1.insert \n\n2.preorder\n\n3.postorder\n\n4.inorder\n\n5.exit\n\n”);
printf(“\n\nEnter ur choice”);
scanf(“%d”,&m);
switch(m)
{
case 0:
tmp=create();
break;
case 1:
insert(tmp);
break;
case 2:
printf(“\n\nDisplay tree in Preorder traversal\n\n”);
preorder(tmp);
break;
case 3:
printf(“\n\nDisplay Tree in Postorder\n\n”);
postorder(tmp);
break;
case 4:
printf(“\n\nInorder\n\n”);
inorder(tmp);
break;
case5:
exit(0);
}
}
while(n!=5);

getch();
}
void insert(NODE *root)
{
NODE *newnode;
if(root==NULL)
{
newnode=create();
root=newnode;

53
}
else
{
newnode=create();
while(1)
{
if(newnode->data<root->data)
{
if(root->llink==NULL)
{
root->llink=newnode;
break;
}
root=root->llink;
}
if(newnode->data>root->data)
{
if(root->rlink==NULL)
{
root->rlink=newnode;
break;
}
root=root->rlink;
}
}
}
}
NODE *create()
{
NODE *newnode;
int n;
newnode=(NODE*)malloc(sizeof(NODE));
printf(“\n\nEnter the Data “);
scanf(“%d”,&n);
newnode->data=n;
newnode->llink=NULL;
newnode->rlink=NULL;
return(newnode);
}

void postorder(NODE *tmp)

{
if(tmp!=NULL)
{
postorder(tmp->llink);

54
postorder(tmp->rlink);
printf(“%d->”,tmp->data);
}
}
void inorder(NODE *tmp)
{
if(tmp!=NULL)
{
inorder(tmp->llink);
printf(“%d->”,tmp->data);
inorder(tmp->rlink);
}
}
void preorder(NODE *tmp)
{
if(tmp!=NULL)
{
printf(“%d->”,tmp->data);
preorder(tmp->llink);
preorder(tmp->rlink);
}
}

OUTPUT

0. Create

1.insert

2.preorder

3.postorder

4.inorder

5.exit

Enter ur choice 0

Enter the Data 3

Enter ur choice 1

Enter the Data 7

55
Enter ur choice 1

Enter the Data 8

Enter ur choice 1

Enter the Data 6

Enter ur choice 1

Enter the Data 4

Enter ur choice2

Display tree in Preorder traversal

3->7->6->4->8

Enter ur choice3

Display tree in Postorder 4 -> 6 -> 8 -> 7 ->3

Enter ur choice4

Inorder

3 -> 4 -> 6 -> 7 -> 8

Enter ur choice 5

VIVA (PRE & POST LAB) QUESTIONS

1. What are the data structures used for BinaryTrees?


2. Explain implementation of traversal of a binarytree.
3. How to perform insertion into a binarytree.
4. Define post-ordertraversal.
5. Define in-ordertraversal.

RESULT

Thus the C program to implement binary tree and its operation was completed
successfully.

56
Ex.No:6 IMPLEMENTATION OF BINARY SEARCH TREES
AIM

To write a C program to implement the binary search trees.

PRE LAB DISCUSSION

A binary search tree (BST) is a tree in which all nodes follows the below mentioned properties

The left sub-tree of a node has key less than or equal to its parent node'skey.
The right sub-tree of a node has key greater than or equal to its parent node's
key.Thus, a binary search tree (BST) divides all its sub-trees into two segments; left sub-
tree and right sub-tree and can be definedas
left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

Following are basic primary operations of a tree which are following.


Search − search an element in atree.
Insert − insert an element in atree.
Delete – removes an existing node from thetree
Preorder Traversal − traverse a tree in a preordermanner.
Inorder Traversal − traverse a tree in an inordermanner.
Postorder Traversal − traverse a tree in a postordermanner.

ALGORITHM

Step 1: Start the process.


Step 2: Initialize and declare variables.
Step 3: Construct the Tree
Step 4: Data values are given which we call a key and a binary search tree
Step 5: To search for the key in the given binary search tree, start with theroot
node and Compare the key with the data value of the root node. Ifthey

57
match, return the root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by
using the left subtree.
Step 7: Otherwise, repeat the same process with the right subtree until either a
match is found or the subtree under consideration becomes an empty tree.
Step 8:Terminate

PROGRAM
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>

struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
}*t,*temp;

int element;
void inorder(struct tree *);
void preorder(struct tree *);
void postorder(struct tree *);
struct tree * create(struct tree *, int);
struct tree * find(struct tree *, int);
struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *);
struct tree * findmax(struct tree *);
void main()
{
int ch;

do
{
printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");
printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n");
printf("\nEnter ur choice :");
scanf("%d",&ch);
switch(ch)
{

58
case1:
printf("\nEnter the data:");
scanf("%d",&element);
t=create(t,element);
inorder(t);
break;
case2:
printf("\nEnter the data:");
scanf("%d",&element);
t=insert(t,element);
inorder(t);
break;
case3:
printf("\nEnter the data:");
scanf("%d",&element);
t=del(t,element);
inorder(t);
break;
case4:
printf("\nEnter the data:");
scanf("%d",&element);
temp=find(t,element);
if(temp->data==element)
printf("\nElement %d is at %d",element,temp);
else
printf("\nElement is not found");
break;
case 5:

temp=findmin(t);
printf("\nMax element=%d",temp->data);
break;
case6:
temp=findmax(t);
printf("\nMax element=%d",temp->data);
break;
case7:
inorder(t);
break;
case8:
preorder(t);
break;
case9:
postorder(t);
break;
case 10:exit(0);

59
}
}while(ch<=10);
}

struct tree * create(struct tree *t, int element)


{
t=(struct tree *)malloc(sizeof(structtree));
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}

struct tree * find(struct tree *t, int element)


{
if(t==NULL)
return NULL;
if(element<t->data)
return(find(t->lchild,element));
else
if(element>t->data)
return(find(t->rchild,element));
else
return t;
}

struct tree *findmin(struct tree *t)


{
if(t==NULL)
return NULL;
else
if(t->lchild==NULL)
return t;
else
return(findmin(t->lchild));
}

struct tree *findmax(struct tree *t)


{
if(t!=NULL)
{
while(t->rchild!=NULL)
t=t->rchild;
}
return t;
}
60
struct tree *insert(struct tree *t,int element)
{
if(t==NULL)
{
t=(struct tree *)malloc(sizeof(struct tree));
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}
else
{
if(element<t->data)
{
t->lchild=insert(t->lchild,element);
}
else
if(element>t->data)
{
t->rchild=insert(t->rchild,element);
}
else

if(element==t->data)
{
printf("element already present\n");
}
return t;
}
}

struct tree * del(struct tree *t, int element)


{
if(t==NULL)
printf("element not found\n");
else
if(element<t->data)
t->lchild=del(t->lchild,element);
else
if(element>t->data)
t->rchild=del(t->rchild,element);
else
if(t->lchild&&t->rchild)
{
temp=findmin(t->rchild);
t->data=temp->data;

61
t- >rchild=del(t->rchild,t->data);
}
else
{
temp=t;
if(t->lchild==NULL)
t=t->rchild;
else
if(t->rchild==NULL)
t=t->lchild;
free(temp);
}
return t;
}

void inorder(struct tree *t)


{
if(t==NULL)
return;
else
{
inorder(t->lchild);
printf("\t%d",t->data);
inorder(t->rchild);
}
}

void preorder(struct tree *t)


{
if(t==NULL)
return;
else
{
printf("\t%d",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}

void postorder(struct tree *t)


{
if(t==NULL)
return;
else
{
postorder(t->lchild);

62
postorder(t->rchild);
printf("\t%d",t->data);
}
}

OUTPUT

BINARY SEARCH TREE


****** ****** ****
Main Menu

1. Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :1

Enter the data:10


10
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:20


10 20
BINARY SEARCH TREE

63
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:30


10 20 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:25


10 20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin

64
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :4

Enter the data:25

Element 25 is at 2216
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :5

Max element=10
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :6

Max element=30
BINARY SEARCH TREE
****** ****** ****
Main Menu

65
1. Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :7
10 20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :8
10 20 30 25
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :9
25 30 20 10
BINARY SEARCH TREE
****** ****** ****

66
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :3

Enter the data:10


20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :10

VIVA (PRE & POST LAB) QUESTIONS

1. Write the various operation performed in the binary searchtree?


2. How many nodes will be there in given nthlevel?
3. Write the necessary condition for inserting element intoBST
4. How will you find the maximum and minimum element inBST?
5. How will you perform deletion in BST with 2children

RESULT

Thus the C program to implement the binary search trees was completed successfully.

67
Ex.No:7 IMPLEMENTATION OF AVL TREES

AIM

To write a C program to implement AVL trees.

PRE LAB DISCUSSION

AVL tree is a self balanced binary search tree. That means, an AVL tree is also a binary
search tree but it is a balanced tree. A binary tree is said to be balanced, if the difference between
the hieghts of left and right subtrees of every node in the tree is either -1, 0 or +1. In other words,
a binary tree is said to be balanced if for every node, height of its children differ by at most one.
In an AVL tree, every node maintains a extra information known as balance factor.
An AVL tree is defined as follows...

An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of every node is
either -1, 0 or +1.

Balance factor of a node is the difference between the heights of left and right subtrees of that
node. The balance factor of a node is calculated either height of left subtree - height of right
subtree (OR) height of right subtree - height of left subtree.

AVL Tree Rotations

In AVL tree, after performing every operation like insertion and deletion we need to check the
balance factor of every node in the tree. If every node satisfies the balance factor condition then
we conclude the operation otherwise we must make it balanced. We use rotation operations to
make the tree balanced whenever the tree is becoming imbalanced due to any operation.

Rotation operations are used to make a tree balanced.

Rotation is the process of moving the nodes to either left or right to make tree balanced.

68
There are four rotations and they are classified into two types.

ALGORITHM

Step 1: Start
Step 2: Insert the new element into the tree using Binary Search Tree insertion logic.
Step 3: After insertion, check the Balance Factor of every node.
If the Balance Factor of every node is 0 or 1 or -1 then go for nextoperation.
If the Balance Factor of any node is other than 0 or 1 or -1 then tree is said to be
imbalanced. Then perform the suitable Rotation to make it balanced. And go for
next operation.
Step 4: Compare, the search element with the value of root node in the tree.
If search element is larger, then continue the search process in right subtree.
If we reach to the node with search value, then display "Element is found" and
terminate the function.
Step 5: Stop

69
PROGRAM

#include<stdio.h>
#include<malloc.h>
typedef enum { FALSE ,TRUE } ;
struct node
{
int info;
int balance;
struct node *lchild;
struct node *rchild;
};
struct node *insert (int , struct node *, int *);
struct node* search(struct node *,int);

struct node* search(struct node *ptr,int info)


{
if(ptr!=NULL)
if(info < ptr->info)
ptr=search(ptr->lchild,info);
else if( info > ptr->info)
ptr=search(ptr->rchild,info);
return(ptr);
}/*End of search()*/

struct node *insert (int info, struct node *pptr, int *ht_inc)
{
struct node *aptr;
struct node *bptr;
if(pptr==NULL)
{
pptr = (struct node *) malloc(sizeof(structnode));
pptr->info =info;
pptr->lchild = NULL;
pptr->rchild = NULL;
pptr->balance = 0;
*ht_inc = TRUE;
return (pptr);
}
if(info < pptr->info)
{
pptr->lchild = insert(info, pptr->lchild, ht_inc);
if(*ht_inc==TRUE)
{
switch(pptr->balance)
{
case -1: /* Right heavy */

70
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = 1;
break;
case 1: /* Left heavy */
aptr = pptr->lchild;
if(aptr->balance == 1)
{
printf("Left to Left Rotation\n");
pptr->lchild= aptr->rchild;
aptr->rchild = pptr;
pptr->balance = 0;
aptr->balance=0;
pptr = aptr;
}
else
{
printf("Left to rightrotation\n");
bptr =aptr->rchild;
aptr->rchild =bptr->lchild;
bptr->lchild =aptr;
pptr->lchild =bptr->rchild;
bptr->rchild =pptr;

if(bptr->balance == 1 )
pptr->balance = -1;
else
pptr->balance = 0;
if(bptr->balance == -1)
aptr->balance = 1;
else
aptr->balance = 0;
bptr->balance=0;
pptr=bptr;
}
*ht_inc = FALSE;
}/*End of switch */
}/*End of if */
}/*End of if*/
if(info > pptr->info)
{
pptr->rchild = insert(info, pptr->rchild, ht_inc);
if(*ht_inc==TRUE)
{

71
switch(pptr->balance)
{
case 1: /* Left heavy */
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = -1;
break;
case -1: /* Right heavy */
aptr = pptr->rchild;
if(aptr->balance == -1)
{
printf("Right to Right Rotation\n");
pptr->rchild= aptr->lchild;
aptr->lchild = pptr;
pptr->balance = 0;
aptr->balance=0;
pptr = aptr;
}
else
{
printf("Right to LeftRotation\n");
bptr =aptr->lchild;
aptr->lchild =bptr->rchild;
bptr->rchild =aptr;
pptr->rchild =bptr->lchild;
bptr->lchild =pptr;
if(bptr->balance == -1)
pptr->balance = 1;
else
pptr->balance = 0;
if(bptr->balance == 1)
aptr->balance = -1;
else
aptr->balance = 0;
bptr->balance=0;
pptr = bptr;
}/*End of else*/
*ht_inc = FALSE;
}/*End of switch */
}/*End of if*/
}/*End of if*/

return(pptr);
}/*End of insert()*/

72
void display(struct node *ptr,int level)
{
int i;
if ( ptr!=NULL )
{
display(ptr->rchild, level+1);
printf("\n");
for (i = 0; i < level; i++)
printf(" ");
printf("%d", ptr->info);
display(ptr->lchild, level+1);
}/*End of if*/
}/*End of display()*/

void inorder(struct node *ptr)


{
if(ptr!=NULL)
{
inorder(ptr->lchild);
printf("%d ",ptr->info);
inorder(ptr->rchild);
}
}/*End of inorder()*/
main()
{
int ht_inc;
int info ;
int choice;
struct node *root = (struct node *)malloc(sizeof(struct node));
root = NULL;

while(1)
{
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value to be inserted : ");
scanf("%d", &info);
if( search(root,info) == NULL )
root = insert(info, root, &ht_inc);

73
else
printf("Duplicate value ignored\n");
break;
case 2:

if(root==NULL)
{
printf("Tree is empty\n");
continue;
}
printf("Tree is :\n");
display(root, 1);
printf("\n\n");
printf("Inorder Traversal is: ");
inorder(root);
printf("\n");
break;
case 3:
exit(1);
default:
printf("Wrong choice\n");

}/*End of switch*/
}/*End of while*/
}/*End of main()*/

OUTPUT

74
VIVA (PRE & POST LAB) QUESTIONS

1. How is an AVL tree better than a binary searchtree?


2. Create an AVL tree using the following sequence of data: 16, 27, 9, 11, 36, 54.
3.Given an empty AVL tree, how would you construct AVL tree when a set of numbers
are given without performing anyrotations?
4. Which rotation is done when the new node is inserted in the right sub-tree of the right
sub-tree of the criticalnode?
5. How to insert a new node into an AVLtree.

RESULT

Thus the C program to implement AVL tree was completed successfully.

75
Ex.No:8.1 LINEARSEARCH

AIM

To write a C program to implement the concept of linear search.

PRE LAB DISCUSSION

Linear search is a very simple search algorithm. In this type of search, a sequential search
is made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.

To search the number 33 in the array given below, linear search will go step by step in a
sequential order starting from the first element in the given array.

ALGORITHM

Step 1: Start with the first item in the list.


Step 2: Compare the current item to thetarget
Step 3: If the current value matches the target then we declare victory and stop.
Step 4: If the current value is less than the target then set the current item to be the next
item and repeat from 2.
Step 5: Stop.

76
PROGRAM

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20];
int i,size,sech;
printf("\n\t-- Linear Search --\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);}
printf("Enter the element to be searched:");
scanf("%d",&sech);
for(i=0; i<size; i++)
{
if(sech==arr[i])
{
printf("Element exits in the list at position : %d",i+1);
break;
}
}getch();
}

OUTPUT

-- Linear Search --
Enter total no. of elements : 5
Enter 1 element : 10
Enter 2 element :4
Enter 3 element :2
Enter 4 element : 17
Enter 5 element : 100
Enter the element to be searched: 17
Element exits in the list at position : 4

77
VIVA (PRE & POST LAB) QUESTIONS

1. Given a list of numbers a[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}. Search
for value 19 using linear search technique.
2. During linear search, when the record is present in first position then how many
comparisons aremade
3. Is a linear search faster than a binarysearch?
4. What is the best case for linearsearch?
5. During linear search, when the record is present in last position then how many
comparisons aremade?

RESULT

Thus the C program to implement linear search was executed successfully.

78
Ex.No:11.2 BINARY SEARCH

AIM

To write a C program to implement the concept of binary search.

PRE LAB DISCUSSION

Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle
of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.
Repeatedly check until the value is found or the interval isempty.

ALGORITHM

Step 1: Set the list to be the whole list


Step 2: Find the middle value of the list
Step 3: If the middle value is equal to the target then we declare victory and stop.
Step 4: If the middle item is less than the target, then we set the new list to be the upper
half of the old list and we repeat from step 2 using the new list.
Step 5: If the middle value is greater than the target, then we set the new list to be the
bottom half of the list, and we repeat from step 2 with the new list.
Step 6: Stop.

79
PROGRAM

#include<stdio.h>
#include<conio.h>
void main(){
int n,i,search,f=0,low,high,mid,a[20];
clrscr();
printf("Enter the nvalue:");
scanf("%d",&n);
for(i=1;i<=n;i++){
printf("Enter the number in ascending order a[%d]=",i);
scanf("%d",&a[i]);
}
printf("Enter the search element:");
scanf("%d",&search);
low=1;
high=n;
while(low<=high){
mid=(low+high)/2;
if(search<a[mid]){
high=mid-1;
}
elseif(search>a[mid]){
low=mid+1;
}
else{
f=1;
printf("obtained in the position %d:",mid);
getch();
exit();
}
}
if(f==0)
printf("not present");
getch();
}
OUTPUT

Enter the n value:5


Enter the number in ascending order a[1]=10
Enter the number in ascending order a[2]=8
Enter the number in ascending order a[3]=9
Enter the number in ascending order a[4]=24
Enter the number in ascending order a[5]=1
Enter the search element:9
obtained in the position 3:

80
VIVA (PRE & POST LAB) QUESTIONS

1. Given an array arr = {5,6,77,88,99} and key = 88; How many iterations are done until the
element isfound?
2. Which technique of searching an element in an array would you prefer touse?
3. What does the following piece of codedo?
{
f=1;
printf("obtained in the position %d:",mid);
}
4. What is the best case for binarysearch?

RESULT

Thus the C program to implement the binary search was completed successfully.

81
Ex.No:8.3 BUBBLE SORT

AIM

To write a C program to implement the concept of bubble sort.

PRE LAB DISCUSSION

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.

Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 >4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 >2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs
one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8)
( 1 2 4 5 8 ) –> ( 1 2 4 5 8)
( 1 2 4 5 8 ) –> ( 1 2 4 5 8)
( 1 2 4 5 8 ) –> ( 1 2 4 5 8)

82
ALGORITHM

Step 1: Start.
Step 2: Repeat Steps 3 and 4 for i=1 to 10
Step 3: Set j=1
Step 4: 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 InnerLoop]

[End of Step 1 Outer Loop]


Step 5: Stop.
PROGRAM

#include<stdio.h>
#include<conio.h>
void main(){
int n, i, j, temp , a[100];
printf("Enter the total integers you want to enter (make it less than 100):\n");
scanf("%d",&n);
printf("Enter the %d integer array elements:\n",n);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++){
for(j=0;j<n-i-1;j++){
if(a[j+1]<a[j]){
temp = a[j];
a[j] = a[j+1];
a[j+1] =temp;
}
}
}
printf("The sorted numbers are:");

83
for(i=0;i<n;i++){
printf("%3d",a[i]);
}
getch();
}

OUTPUT

Enter the total integers you want to enter (make it less than 100):
5
Enter the 5 integer array elements:
99
87
100
54
150
The sorted numbers are: 54 87 99 100 150

VIVA (PRE & POST LAB) QUESTIONS

1. Sort the elements 77, 49, 25, 12, 9, 33, 56, 81 using bubblesort
2. The given array is arr = {1,2,4,3}. Bubble sort is used to sort the array elements. How
many iterations will be done to sort thearray?
3. The given array is arr = {1,2,4,3}. Bubble sort is used to sort the array elements. How
many iterations will be done to sort the array with improvisedversion?
4. What does the following piece of codedo?
if(a[j+1]<a[j])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] =temp;
}

RESULT

Thus the C program for the concept of bubble sort was implemented successfully.

84
Ex.No:11.4 INSERTION SORT

AIM

To write a C program to implement the concept of insertionsort.

PRE LAB DISCUSSION

Insertion sort is an in-place comparison-based sorting algorithm. Here, a sub-list is


maintained which is always sorted. For example, the lower part of an array is maintained to be
sorted. An element which is to be inserted in this sorted sub-list, has to find its appropriate place
and then it has to be inserted there.

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in
our hands.

ALGORITHM

Step 1: Start with an empty left hand [sorted array] and the cards face down on the table
[unsorted array].
Step 2:Then remove one card [key] at a time from the table [unsorted array], and insert it
into the correct position in the left hand [sorted array].
Step 3: To find the correct position for the card, we compare it with each of the cards
already in the hand, from right to left.
Step 4:Stop

85
PROGRAM

#include<stdio.h>
void inst_sort(int[]);
void main()
{
int num[5],count;
printf("\n enter the five elements to sort:\n");
for(count=0;count<5;count++)
scanf("%d",&num[count]);
inst_sort(num); /*function call for insertion sort*/
printf("\n\n elements after sorting:\n"); for(count=0;count<5;count++)
printf("%d\n",num[count]);
}
void inst_sort(int num[])
{ /* function definition for insertion sort*/
int i,j,k;
for(j=1;j<5;j++) { k=num[j];
for(i=j-1;i>=0&&k<num[i];i--)
num[i+1]=num[i];
num[i+1]=k;
}}

OUTPUT

enter the five elements to sort:

54321

elements after sorting:


1
2
3
4
5

VIVA (PRE & POST LAB) QUESTIONS

1. Which sorting algorithms in its typical implementation gives best performance when applied
on an array which is sorted or almost sorted (maximum 1 or two elements aremisplaced).
2. Which sorting algorithm will take least time when all elements of input array are identical?
3.Mention the uses of insertionsort.
4. Consider an array of elements arr[5]= {5,4,3,2,1} , what are the steps of insertions done while
doing insertion sort in thearray.

RESULT

Thus the C program to implement insertion sort was completed successfully.


86
Ex.No:12.1 HASHING WITH SEPARATE CHAINING

AIM

To write a C program to implement the concept of hashing using separate chaining.

PRE LAB DISCUSSION

In hashing there is a hash function that maps keys to some values. But these hashing
function may lead to collision that is two or more keys are mapped to same value. Chain hashing
avoids collision. The idea is to make each cell of hash table point to a linked list of records that
have same hash functionvalue.
Let’s create a hash function, such that our hash table has ‘N’ number of buckets. To
insert a node into the hash table, we need to find the hash index for the given key. And it could be
calculated using the hashfunction.
Example: hashIndex = key % noOfBuckets
Insert: Move to the bucket corresponds to the above calculated hash index and insert the new
node at the end of the list.

ALGORITHM

Step 1:Start
Step 2:Create Table size
Step 3: Create hash function
Step 4: To insert a node into the hash table, we need to find the hash index for the given
key. And it could be calculated using the hash function.

87
Step 5: Display hash entry.
Step 6: Stop
PROGRAM
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 3
struct node
{
int data;
struct node *next;
};
struct node *head[TABLE_SIZE]={NULL},*c,*p;
void insert(int i,int val)
{
struct node * newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=val;
newnode->next = NULL;
if(head[i] == NULL)
head[i] = newnode;
else
{
c=head[i];
while(c->next != NULL)
c=c->next;
c->next=newnode;
}
}
void display(int i)
{
if(head[i] == NULL)
{
printf("No Hash Entry");
return;
}
else

88
{
for(c=head[i];c!=NULL;c=c->next)
printf("%d->",c->data);
}
}
main()
{

int opt,val,i;
while(1)
{
printf("\nPress 1. Insert\t 2. Display \t3. Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\nenter a value to insert into hash table\n");
scanf("%d",&val);
i=val%TABLE_SIZE;
insert(i,val);
break;
case 2:
for(i=0;i<TABLE_SIZE;i++)
{
printf("\nentries at index %d\n",i);
display(i);
}
break;
case 3: exit(0);
}
}
OUTPUT

89
VIVA (PRE & POST LAB) QUESTIONS

1. If several elements are competing for the same bucket in the hash table, what is itcalled?
2. How to insert a node in hashtable?
3. What is sizeof()function?
4. How to delete a node from hashtable.

RESULT

Thus the C program to implement hashing using separate chaining was completed
successfully.

90
TOPIC BEYOND SYLLABUS

91
Ex.No:13 IMPLEMENTATION DOUBLY LINKEDLIST

AIM

To write a C program to implement doubly linked list with Insert, Delete and Display
operations.

PRE LAB DISCUSSION

Doubly linked list is a sequence of elements in which every node has link to its previous
node and next node.

Traversing can be done in both directions and displays the contents in the wholelist.

Link1 field stores the address of the previous node and Link2 field stores the address of the
next node. The Data Item field stores the actual value of that node. If we insert a data into the
linked list, it will be look like asfollows:

In doubly linked list contains three fields. In this, link of two nodes allow traversal of the
list in either direction. There is no need to traverse the list to find the previous node. We can
traverse from head to tail as well as tail to head.

92
ALGORITHM

Step 1: Start
Step 2: Creation: Get the number of elements to create the list. Then create the node having
the Structure: BLINK, DATA , FLINK and store the elements in Data field. Link them
together to form a doubly linked list.
Step 3: Insertion: Get the number to be Inserted, create a new node to store the value.
Search the list and insert the node in its right position.
Step 4: Deletion: Get the number to be deleted. Search the list from the beginning and try
to locate node p with DATA. If found then delete the node.
Step 5: FLINK P’s previous node to P’s Next node. BLINK P’s Next node to P’s Previous
node else display “Data notFound”.
Step 6: Display: Display all the nodes in the list.
Step 7: Stop.

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
typedef struct list
{
int no;
struct list *next;
struct list *pre;

93
}LIST;
LIST *p,*t,*h;
void create( void );
void insert( void );
void delet( void);
void display ( void );
int j,pos,k=1,count;
void main()
{
int n,i=1,opt;
clrscr();
p = NULL;
printf( "Enter the no of nodes :\n " );
scanf( "%d",&n );
count = n;
while( i <= n)
{ create();
i++;
}
printf("\nEnter your option:\n");
printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n");
do
{
scanf("%d",&opt);
switch( opt ){
case 1:
insert();
count++;
break;

case 2:

94
delet();
count--;
if ( count == 0 )
{
printf("\n List is empty\n");
}
break;

case 3:
printf("List elements are:\n");
display();
break;
}
printf("\nEnter your option \n");
}while( opt != 4 );
getch();
}

void create ( )
{
if( p == NULL )
{
p = ( LIST * ) malloc ( sizeof ( LIST ) );
printf( "Enter the element:\n" );
scanf( "%d",&p->no );
p->next = NULL;
p->pre = NULL;
h = p;
}
else
{

95
t= ( LIST * ) malloc (sizeof( LIST ));
printf( "\nEnter the element" );
scanf( "%d",&t->no );
t->next = NULL;
p->next = t;
t->pre = p;
p = t;
}
}
void insert()
{
t=h;
p = ( LIST * ) malloc ( sizeof(LIST) );
printf("Enter the element to be insrted:\n");
scanf("%d",&p->no);
printf("Enter the position to insert:\n");
scanf( "%d",&pos );
if( pos == 1 )
{
h = p;
h->next = t;
t->pre = h;
h->pre = NULL;
}
else
{
for(j=1;j<(pos-1);j++)
t = t->next;
p->next = t->next;
t->next = p;
p->pre = t;

96
}
}
void delete()
{
printf("Enter the position to delete:\n");
scanf( "%d",&pos );
if( pos == 1)
{
h = h->next;
h->pre = NULL;
}
else
{
t=h;
for(j=1;j<(pos-1);j++)
t = t->next;
t->next = t->next->next;
t->next->pre = t;
free( t->next );
}
}
void display()
{
t= h;
while( t->next != NULL )
{
printf("%d\n",t->no);
t = t->next;
}
printf( "%d",t->no );
}

97
OUTPUT

Enter the no of nodes: 3


Enter the element3
Enter youroption:
1. Insert 2.Delete 3.Display4.Exit
3
List elements are:
123
Enter your option 1
Enter the element to be inserted:22
Enter the position to insert:1
Enter your option 3
List elements are:
22 1 2 3
Enter your option 1
Enter the element to be inserted:
11
Enter the position to insert:5
Enter your option 3
List elements are:
22 1 2 3 11
Enter your option
2
Enter the position todelete:
1
Enter your option
3
List elements are:
1 2 3 11
Enter your option 4

98
VIVA (PRE & POST LAB) QUESTIONS

1. How will you traverse double linkedlist?


2. Give the structure of node in a doubly linkedlist.
3. Specify the steps to insert an element in Doubly LinkedList.
4. How to delete an element from a doubly linkedlist.

RESULT

Thus the C program to implement Doubly Linked List was completed successfully.

99

You might also like