DS Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

ACHARYAINSTITUTEOFTECHNOLOGY

Bengaluru–560 107.

Department of Electronics and


Communication Engineering

LAB MANUAL

Academic Year : 2023–24 (EVEN SEMESTER)


Programme (UG/PG) : UG
Year/ Semester : IV
Course Code : BECL456D
Course Title : Data Structures using C Lab

Prepared By
Dr. Nataraju A B
Mr. Shadakshari

Reviewed By
Dr. Nataraju A B
Asst. Prof., Dept. of ECE, AIT

Approved By
Dr. Rajeswari
Prof and Head, Department of ECE, AIT
DEPARTMENTOFELECTRONICSANDCOMMUNICATIONENGINEERING

VISION STATEMENT

“To be a premier engineering department with excellence in teaching, research and innovation, to meet
the global industrial standards and to have significant impact on the wellbeing of the society”.
MISSIONSTATEMENT

1. To provide student centric learning environment, inculcate profound knowledge in


both fundamental and applied areas of science and technology.
2. To train and mentor the students in developing leadership qualities and team building skills.

Program Outcomes(POs)

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 modeling 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 responsible 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 ethicalprinciplesandcommittoprofessionalethicsandresponsibilitiesandnorms of the


engineering practice.

9. Individual and teamwork: 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(PSOs)

PSO1: Analog / Digital Circuit Design: Apply the conceptual knowledge in the analysis and/or
design ,evaluate analog/digital circuits and systems.

PSO2: VLSI , Signal Processing and Embedded Systems : Demonstrate technical competency
in the analysis, design , and validation of components in VLSI , Signal Processing, and
Embedded Systems

PSO3: Communication and Networking: Apply the domain knowledge in the implementation
and performance analysis of Communication Systems and Computer Networks.

Program Educational Objectives (PEOs)

Upon successful completion of the program, the student will be able to

PEO1: Students shall have a successful professional career in industry, academia, R & D organization
or entrepreneur in specialized field of Electronics & Communication engineering and allied disciplines.

PEO2:Students shall be competent, creative and valued professional in the chosen field.

PEO3:Engage in life-long learning and professional development.

PEO4:Become effective global collaborators, leading or participating to address technical, business,


environmental and societal challenges.
Experiments

1. Write a C Program to create a Student record structure to store, N records, each record having the
structure shown below: USN, Student Name and Semester. Write necessary functions a. To display all
the records in the file. b. To search for a specific record based on the USN. In case the record is not
found, suitable message should be displayed. Both the options in this case must be demonstrated. (Use
pointer to structure for dynamic memory allocation)

2 Write a C Program to construct a stack of integers and to perform the following operations on it: a. Push
b. Pop c. Display The program should print appropriate messages for stack overflow, stack underflow,
and stack empty.

3 Write a C Program to convert and print a given valid parenthesized infix arithmetic expression to
postfix expression. The expression consists of single character operands and the binary operators +
(plus), - (minus), * (multiply) and / (divide).

4 Write a C Program to simulate the working of a queue of integers using an array. Provide the following
operations: a. Insert b. Delete c. Display

5 Write a C Program using dynamic variables and pointers to construct a stack of integers using singly
linked list and to perform the following operations: a. Push b. Pop c. Display The program should print
appropriate messages for stack overflow and stack empty.

6 Write a C Program to support the following operations on a doubly linked list where each node consists
of integers: a. Create a doubly linked list by adding each node at the front. b. Insert a new node to the
left of the node whose key value is read as an input c. Delete the node of a given data, if it is found,
otherwise display appropriate message. d. Display the contents of the list. (Note: Only either (a,b and d)
or (a, c and d) may be asked in the examination)

7 Write a C Program a. To construct a binary search tree of integers. b. To traverse the tree using all the
methods i.e., inorder, preorder and postorder. c. To display the elements in the tree.

8 Write recursive C Programs for a. Searching an element on a given list of integers using the Binary
Search method. b. Solving the Towers of Hanoi problem.

9 Write a program to traverse a graph using BFS method.


Write a program to check whether given graph is connected or not using DFS method.

10 Design and develop a program in C that uses Hash Function H:K->L as H(K)=K mod m(reminder
method) and implement hashing technique to map a given key K to the address space L. Resolve the
collision (if any) using linear probing
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

EXPERIMENT–1 : Student record (basic C operations)

Write a C Program to create a Student record structure to store, N records, each record having the structure
shown below: USN, Student Name and Semester. Write necessary functions a. To display all the records in
the file. b. To search for a specific record based on the USN. In case the record is not found, suitable message
should be displayed. Both the options in this case must be demonstrated. (Use pointer to structure for dynamic
memory allocation)

The student data structure contain basic details about a student such as name, usn, result, address, …..
for example:
struct student {
char firstName[50]; // Student’s Name
int roll; // Student’s Roll number
float marks; // Student’s marks
}

// C Program to Store Information of Students Using Structure


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Create the student structure


struct Student {
char USN[12];
char name[20];
int Semester;
};

// Driver code
int main()
{
int i = 0, n = 5, stFound=0;
char usn[12];

struct Student *student;

printf("Enter No of students in the list :");


scanf("%d", &n);

// Allocate memory for Student's data structure


student = (struct Student *) malloc (n * sizeof(struct Student));

// Read the 'n' student's details


for (i=0; i<n; i++)
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

{
printf("Enter the student %d details : \n", i+1);

// Get the students data


printf("USN : ");
scanf("%s", student[i].USN);

printf("Name : ");
scanf("%s", student[i].name);

printf("Semester : ");
scanf("%d", & student[i].Semester);
}

// Print the Student's information


printf("Student Records:\n\n");
for (i = 0; i < n; i++)
{
printf("\tUSN = %s\n", student[i].USN);
printf("\tName = %s\n", student[i].name);
printf("\tSemester = %d\n", student[i].Semester);
printf("\n");
}

printf("Enter the USN to be searched for : ");


scanf("%s", usn);

for (i = 0; i < n; i++)


{
if(!strcmp(usn, student[i].USN)) {
printf("\tStudent with USN = %s is(are)\n", student[i].USN);
printf("\tUSN = %s\n", student[i].USN);
printf("\tName = %s\n", student[i].name);
printf("\tSemester = %d\n", student[i].Semester);
printf("\n");

stFound = 1; // use this flag to print when no student


// record is found in the list
}
}

if(stFound == 0)
printf("\tThere are No Student found with USN = %s\n", usn);
return 0;
}
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Example O/P – 1

Enter No of students in the list :1


Enter the student 1 details :
USN : 1111
Name : aaaa
Semester : 3
Student Records:

USN = 1111
Name = aaaa
Semester = 3

Enter the USN to be searched for : 12


There are No Student found with USN = 12

Example O/P – 2

Enter No of students in the list :3


Enter the student 1 details :
USN : 11
Name : aa
Semester : 3
Enter the student 2 details :
USN : 23
Name : bb
Semester : 4
Enter the student 3 details :
USN : 11
Name : cc
Semester : 1
Student Records:

USN = 11
Name = aa
Semester = 3

USN = 23
Name = bb
Semester = 4

USN = 11
Name = cc
Semester = 1

Enter the USN to be searched for : 11


Student with USN = 11 is(are)
USN = 11
Name = aa
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Semester = 3

Student with USN = 11 is(are)


USN = 11
Name = cc
Semester = 1

Example O/P – 3

Enter No of students in the list :2


Enter the student 1 details :
USN : 11
Name : aa
Semester : 4
Enter the student 2 details :
USN : 22
Name : bb
Semester : 2
Student Records:

USN = 11
Name = aa
Semester = 4

USN = 22
Name = bb
Semester = 2

Enter the USN to be searched for : 1


There are No Student found with USN = 1
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Experiment – 2 : Stack using array

Write a C Program to construct a stack of integers and to perform the following


operations on it:
a. Push ( ) b. Pop ( ) c.Display ( )
The program should print appropriate messages for stack overflow, stack underflow,
and stack empty.

/** Stack implementation using array in C language. */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // For INT_MIN

#define SIZE 100

// Create a stack with capacity of 100 elements


int stack[SIZE];

// Initially stack is empty


int top = -1;

/* Function declaration to perform push and pop on stack */


void push(int element);
int pop();

int main()
{
int choice, data;

while(1)
{
/* Menu */
printf("------------------------------------\n");
printf(" STACK IMPLEMENTATION PROGRAM \n");
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

printf("------------------------------------\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Size\n");
printf("4. Exit\n");
printf("------------------------------------\n");
printf("Enter your choice: ");

scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter data to push into stack: ");
scanf("%d", &data);

// Push element to stack


push(data);
break;

case 2:
data = pop();

// If stack is not empty


if (data != INT_MIN)
printf("Data => %d\n", data);
break;

case 3:
printf("Stack size: %d\n", top + 1);
break;

case 4:
printf("Exiting from app.\n");
exit(0);
break;

default:
printf("Invalid choice, please try again.\n");
}

printf("\n");
}

return 0;
}
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

/* Function to push a new element in stack. */


void push(int element)
{
// Check stack overflow
if (top >= SIZE)
{
printf("Stack Overflow, can't add more element to stack.\n");
return;
}

// Increase elements count in stack


top++;

// Push element in stack


stack[top] = element;

printf("Data pushed to stack.\n");


}

/* Function to pop element from top of stack. */


int pop()
{
// Check for stack underflow
if (top < 0)
{
printf("Stack is empty.\n");
printf("Hence return INT_MIN as an indication of EMPTY stack.\n");

return INT_MIN;
}

// Return stack top and decrease element count in stack


return stack[top--];
}

Example O/P – 1
------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit

------------------------------------
Enter your choice: 1
Enter data to push into stack: 11
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Data pushed to stack.

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 1
Enter data to push into stack: 22
Data pushed to stack.

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 3
Stack size: 2

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 22

------------------------------------
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

STACK IMPLEMENTATION PROGRAM


------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 11

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Stack is empty.
Hence return INT_MIN as an indication of EMPTY stack.

------------------------------------
Enter your choice: 4
Exiting from app.
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Experiment – 3 : infix -> postfix


Write a C Program to convert and print a given valid parenthesized infix arithmetic expression to postfix
expression. The expression consists of single character operands and the binary operators + (plus), - (minus),
* (multiply) and / (divide).

This program is an example of stack application.

Infix expression can be represented with A+B, the operator is in the middle of the expression.
In postfix expression, the operator will be at end of the expression, such as AB+
We can easily solve problems using Infix notation, but it is not possible for the computer to solve the given
expression, so system must convert infix to postfix, to evaluate that expression.

/* C Program to Convert Infix to Postfix using Stack */

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

void push(char x)
{
// Pre increment push
stack[++top] = x;
}

char pop()
{
// Post decrement POP

if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

return 2;
return 0;
}

int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}
return 0;
}
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Output Test Case 1:


Enter the expression : a+b*c

a b c * +

Output Test Case 2:


Enter the expression : (a+b)*c+(d-a)

a b + c * d a - +

Output Test Case 3:


Enter the expression : ((4+8)(6-5))/((3-2)(2+2))
4 8 + 6 5 - 3 2 - 2 2 + /
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Experiment – 4 : Queue

Write a C Program to simulate the working of a queue of integers using an array. Provide the following
operations: a. Insert b. Delete c. Display

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

#define MAX_SIZE 100

int queue[MAX_SIZE];

int front = -1;


int rear = -1;
int element;

void enqueue(int element)


{
if (rear == MAX_SIZE - 1) {
printf("Queue is full");
return;
}

if (front == -1) {
front = 0;
}

rear++;
queue[rear] = element;
}

int dequeue()
{
if (front == -1 || front > rear) {
printf("Queue is empty");
return -1;
}
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

int element = queue[front];


front++;

return element;
}

void display()
{
int i;

if(front == -1 || rear == -1)


{
printf("\n The QUEUE is empty"); return;
}

printf("\n The elements in QUEUE \n");


for (i=front; i<=rear; i++)
{
printf("<-- %d\t", queue[i]);
}
}

int main()
{
int choice, num, size;

printf("\n Enter the size of QUEUE[MAX=100]:");


scanf("%d",&size);

printf("\n\t QUEUE 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:
{
printf("\n\t Enter element to be Queued : ");
scanf("%d",&num);

enqueue(num);
break;
}
case 2:
{
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

num = dequeue();
printf("\n Dequeued element is : %d ", num);
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;
}

Example O/P – 1

Enter the size of QUEUE[MAX=100]:10

QUEUE OPERATIONS USING ARRAY


--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1

Enter element to be Queued : 11

Enter the Choice:1

Enter element to be Queued : 22

Enter the Choice:1

Enter element to be Queued : 33


Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Enter the Choice:3

The elements in QUEUE


<-- 11 <-- 22 <-- 33

Enter the Choice:2

Dequeued element is : 11
Enter the Choice:3

The elements in QUEUE


<-- 22 <-- 33
Enter the Choice:2

Dequeued element is : 22
Enter the Choice:3

The elements in QUEUE


<-- 33
Enter the Choice:2

Dequeued element is : 33
Enter the Choice:3

The elements in QUEUE

Enter the Choice:2


Queue is empty
Dequeued element is : -1
Enter the Choice:
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Experiment – 5 : Stack Using LL


Write a C Program using dynamic variables and pointers to construct a stack of integers using singly linked
list and to perform the following operations: a. Push b. Pop c. Display The program should print appropriate
messages for stack overflow and stack empty.

In linked list implementation of stack, the nodes are maintained non-contiguously in the memory. Each node
contains a pointer to its immediate successor node in the stack. Stack is said to be overflown if the space left
in the memory heap is not enough to create a node.

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

void push();
void pop();
void display();

struct node
{
int val;
struct node *next;
};
struct node *head;
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

void main ()
{
int choice=0;
printf("\n*********Stack operations using linked list*********\n");
printf("\n----------------------------------------------\n");
while(choice != 4)
{
printf("\nChoose one from the below options...");
printf("\n\t1.Push\n\t2.Pop\n\t3.Show\n\t4.Exit");
printf("\nEnter your choice : ");
scanf("%d",&choice);

switch(choice)
{
case 1:
{
push(); break;
}
case 2:
{
pop(); break;
}
case 3:
{
display(); break;
}
case 4:
{
printf("Exiting...."); break;
}
default:
{
printf("Please Enter valid choice ");
}
}
}
}

void push ()
{
int val;
struct node *ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

printf("Enter the value ");


scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed is %d", val);

}
}

void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow / Stack Empty");
}
else
{
item = head->val;
ptr = head;
head = head->next;
printf("Item popped is %d \n", ptr->val);
free(ptr);
}
}

void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}
}
}

*********Stack operations using linked list*********


----------------------------------------------
Choose one from the below options...
1.Push
2.Pop
3.Show
4.Exit
Enter your choice : 1
Enter the value 11
Item pushed is 11

Choose one from the below options...


1.Push
2.Pop
3.Show
4.Exit
Enter your choice : 22
Please Enter valid choice

Choose one from the below options...


1.Push
2.Pop
3.Show
4.Exit
Enter your choice : 2
Item popped is 11

Choose one from the below options...


1.Push
2.Pop
3.Show
4.Exit
Enter your choice : 2
Underflow / Stack Empty

*********Stack operations using linked list*********


Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

----------------------------------------------
Choose one from the below options...
1.Push
2.Pop
3.Show
4.Exit
Enter your choice : 1
Enter the value 11
Item pushed is 11
Choose one from the below options...
1.Push
2.Pop
3.Show
4.Exit
Enter your choice : 1
Enter the value 22
Item pushed is 22
Choose one from the below options...
1.Push
2.Pop
3.Show
4.Exit
Enter your choice : 3
Printing Stack elements
22
11
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

Experiment – 6 : Doubly Linked List operations


Write a C Program to support the following operations on a doubly linked list where each node consists of
integers: a. Create a doubly linked list by adding each node at the front. b. Insert a new node to the left of the
node whose key value is read as an input c. Delete the node of a given data, if it is found, otherwise display
appropriate message. d. Display the contents of the list. (Note: Only either (a,b and d) or (a, c and d) may be
asked in the examination)
Simple node in a doubly linked list is as follows

struct node {
struct node *next;
int data; // This element may be replaced with any
// application specific structure / class / union / ….
struct node *prev;
}

#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};

struct node *head;


void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any rando
m location\n4.Delete from Beginning\n
5.Delete from last\n6.Delete the node after the given data\n7.Search\n8
.Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("%d",&choice);
switch(choice)
{
case 1:insertion_beginning(); break;
case 2: insertion_last(); break;
case 3: insertion_specified(); break;
case 4: deletion_beginning(); break;
case 5: deletion_last(); break;
case 6: deletion_specified(); break;
case 7: search(); break;
case 8: display(); break;
case 9: exit(0); break;
default: printf("Please enter valid choice..");
}
}
}

void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);

if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}
}

void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}

}
printf("\nnode inserted\n");
}

void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}

void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
Data Structures using C Lab (BECL456D) 4th Sem B.E ECE

void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}

}
Experiment – 7 : Binary Search Tree and its traversal
Write a C Program a. To construct a binary search tree(BST) of integers. b. To traverse the tree using all the
methods i.e., inorder, preorder and postorder. c. To display the elements in the tree.

Types of Traversal of Binary Tree


There are three types of traversals of a binary tree.
➢ Inorder tree traversal
➢ Preorder tree traversal
➢ Postorder tree traversal

//C Program for traversal of the binary search tree

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

struct node
{
int key;
struct node *left;
struct node *right;
};

//return a new node with the given value


struct node *getNode(int val)
{
struct node *newNode;

newNode = malloc(sizeof(struct node));

newNode->key = val;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

//inserts nodes in the binary search tree


struct node *insertNode(struct node *root, int val)
{
if(root == NULL)
return getNode(val);

if(root->key < val)


root->right = insertNode(root->right,val);

if(root->key > val)


root->left = insertNode(root->left,val);

return root;
}

//inorder traversal of the binary search tree


void inorder(struct node *root)
{ // Left, Current, Right
if(root == NULL)
return;

//traverse the left subtree


inorder(root->left);

//visit the root


printf("%d ",root->key);

//traverse the right subtree


inorder(root->right);
}
//preorder traversal of the binary search tree
void preorder (struct node *root)
{ // Current, Left, Right
if(root == NULL)
return;

//visit the root


printf("%d ",root->key);

//traverse the left subtree


preorder(root->left);

//traverse the right subtree


preorder(root->right);
}

//postorder traversal of the binary search tree


void postorder(struct node *root)
{ // Left, Right, Current
if(root == NULL)
return;

//traverse the left subtree


postorder(root->left);

//traverse the right subtree


postorder(root->right);

//visit the root


printf("%d ",root->key);

}
int main()
{
struct node *root = NULL;

int data;
char ch;
/* Do while loop to display various options to select from to
decide the input */
do
{
printf("\nSelect one of the operations::");
printf("\n1. To insert a new node in the Binary Tree");
printf("\n2. To display the nodes (via Inorder Traversal).");
printf("\n3. To display the nodes (via Preorder Traversal).");
printf("\n4. To display the nodes (via Postorder Traversal).\n");
int choice;
scanf("%d",&choice);
switch (choice)
{
case 1 :
printf("\nEnter the value to be inserted : ");
scanf("%d",&data);
root = insertNode(root,data);
break;
case 2 :
printf("\nInorder Traversal of the Binary Tree::\n");
inorder(root);
break;
case 3 :
printf("\nPreorder Traversal of the Binary Tree::\n");
preorder(root);
break;
case 4 :
printf("\nPostorder Traversal of the Binary Tree::\n");
postorder(root);
break;
default :
printf("Wrong Entry\n");
break;
}

printf("\nDo you want to continue (Type y or n)\n");


scanf(" %c",&ch);
} while (ch == 'Y'|| ch == 'y');

return 0;
}

Select one of the operations::


1. To insert a new node in the Binary Tree
2. To display the nodes (via Inorder Traversal).
3. To display the nodes (via Preorder Traversal).
4. To display the nodes (via Postorder Traversal).
1

Enter the value to be inserted : 55

Do you want to continue (Type y or n)


y

Select one of the operations::


1. To insert a new node in the Binary Tree
2. To display the nodes (via Inorder Traversal).
3. To display the nodes (via Preorder Traversal).
4. To display the nodes (via Postorder Traversal).
1

Enter the value to be inserted : 44

Do you want to continue (Type y or n)


y

Select one of the operations::


1. To insert a new node in the Binary Tree
2. To display the nodes (via Inorder Traversal).
3. To display the nodes (via Preorder Traversal).
4. To display the nodes (via Postorder Traversal).
1

Enter the value to be inserted : 70

Do you want to continue (Type y or n)


Y

Select one of the operations::


1. To insert a new node in the Binary Tree
2. To display the nodes (via Inorder Traversal).
3. To display the nodes (via Preorder Traversal).
4. To display the nodes (via Postorder Traversal).
2

Inorder Traversal of the Binary Tree::


44 55 70

Select one of the operations::


1. To insert a new node in the Binary Tree
2. To display the nodes (via Inorder Traversal).
3. To display the nodes (via Preorder Traversal).
4. To display the nodes (via Postorder Traversal).
3

Preorder Traversal of the Binary Tree::


55 44 70

Select one of the operations::


1. To insert a new node in the Binary Tree
2. To display the nodes (via Inorder Traversal).
3. To display the nodes (via Preorder Traversal).
4. To display the nodes (via Postorder Traversal).
Postorder Traversal of the Binary Tree::
44 70 55
Experiment – 8 : Recursion for Binary Search and TOH problem
Write recursive C Programs for a. Searching an element on a given list of integers using the Binary Search
method. b. Solving the Towers of Hanoi problem.

// C program to implement binary search using recursion


#include <stdio.h>

// A recursive binary search function. It returns location


// of x in given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
// checking if there are elements in the subarray
if (r >= l) {

// calculating mid point


int mid = l + (r - l) / 2;

// If the element is present at the middle itself


if (arr[mid] == x)
return mid;

// If element is smaller than mid, then it can only


// be present in left subarray
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}

// Else the element can only be present in right


// subarray
return binarySearch(arr, mid + 1, r, x);
}

// We reach here when element is not present in array


return -1;
}

// driver code
int main(void)
{
// taking a sorted array
int arr[] = { 2, 3, 4, 10, 40 };
int size = sizeof(arr) / sizeof(arr[0]);
// element to be searched
int x = 10;
// calling binary search
int index = binarySearch(arr, 0, size - 1, x);
if (index == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", index);
}

return 0;
}

// BINARY SEARCH USING ITERATIVE METHOD

// C Program to implement binary search using iteration


#include <stdio.h>

// A iterative binary search function. It returns location


// of x in given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
// the loop will run till there are elements in the
// subarray as l > r means that there are no elements to
// consider in the given subarray
while (l <= r) {

// calculating mid point


int m = l + (r - l) / 2;

// Check if x is present at mid


if (arr[m] == x) {
return m;
}

// If x greater than ,, ignore left half


if (arr[m] < x) {
l = m + 1;
}

// If x is smaller than m, ignore right half


else {
r = m - 1;
}
}

// if we reach here, then element was not present


return -1;
}
// driver code
int main(void)
{
// creating a sorted array
int arr[] = { 2, 3, 4, 10, 40 };
int size = sizeof(arr) / sizeof(arr[0]);
// element to be searched
int x = 4;

// calling binary search


int result = binarySearch(arr, 0, size - 1, x);

if (result == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", result);
}

return 0;

.h>

You might also like