0% found this document useful (0 votes)
96 views54 pages

DSA Lab Manual 2024-25

dsa lab manual

Uploaded by

darshangowda0525
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)
96 views54 pages

DSA Lab Manual 2024-25

dsa lab manual

Uploaded by

darshangowda0525
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/ 54

DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND


MANAGEMENT
(Affiliated to VTU, Belagavi and Approved by AICTE, New Delhi)
(Autonomous under VTU)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082

Department of Information Science and Engineering

3 Years Accredited by NBA, New Delhi (Validity: 1-07-2022 to 30-06-2025)


Course Name: Data Structures and Applications
Course Code: 23ISEN32

Scheme: 2023

Prepared by:
Dr. Pooja Nayak S

Associate Professor

Department of Information Science and Engineering

Mrs. Sridevi G M

Assistant Professor

Department of Information Science and Engineering

Mrs. Kavyashree G M

Assistant Professor

Department of Information Science and Engineering

DSATM, Bangalore-82 Page 1


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT


(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi,
Accredited by NBA for 3 years, New Delhi)

VISION OF THE INSTITUTE

To strive at creating the institution a center of highest caliber of learning, so as to create an


overall intellectual atmosphere with each deriving strength from the other to be the best of
engineers, scientists and mathematicians.

MISSION OF THE INSTITUTE


 To serve its region, state, the nation and globally by preparing students to make meaningful
contributions in an increasing complex global society.
 To encourage, reflection on and evaluation of emerging needs and priorities with state of art
infrastructure.
 To support research and services establishing enhancements in technical, health, economic,
human and cultural development.
 To establish inter disciplinary center of excellence.
 To increase the number of Doctorate holders to promote research culture on campus.
QUALITY POLICY

"We, at "Dayananda Sagar Academy of Technology and Management" are committed to


continually improve and deliver competitive quality technical education to the at most
satisfaction of student, their parents and potential employer."

OBJECTIVES & GOALS

1. Creating an academic environment to develop the younger generation and providing quality
professional engineering education at an affordable cost.
2. Create necessary infrastructure on a continuous basis the professional education with the
changing needs of society.
3. Optimum utilization of the infrastructure and resources to achieve excellence in the
engineering courses.
4. Monitor continuously the growth in technology parts of the world and address all aspects of
development of human resource (both from academic and supporting staff) and students to be in
tune with state of the art technology and engineering practices.
5. Facilitate greater Industry, Institute, and Interaction so as to empower the students with
practical knowledge.
6. Institute various quality assurance systems.
7. Adopting learning beyond curriculum process.
8. Initiate systems of learning which are based on enable students to acquire skills relevant to their
career.
9. To continuous monitor, asses evaluate the various academic programs adopting outcome-based
education.

DSATM, Bangalore-82 Page 2


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

DATA STRUCTURES AND APPLICATIONS


LABORATORY
Outcome-Based Education (OBE) and Choice Based Credit System (CBCS)
(Effective from the academic year 2023 – 24)

Course Code 23ISEN32 CIE Marks 50


Teaching Hours/Week (L: T:P: S) 2:0:2:0 SEE Marks 50
Total Hours of Pedagogy -- Total Marks 100
Credits 03 Exam Hours 03
List of problems for which students should develop the program and execute in the
Laboratory
Sl. No. Experiments/Programs Page No.
1 Develop a C Program to store movie Data with the fields: Title, Genre, Actor,
1
Actress, and rating in an appropriate data structure.
2 Given a mathematical expression exp, write a program to examine whether the
4
parentheses in the expression are balanced.
3 Implement a program in C to convert an Infix Expression to a Postfix Expression.
The program should support both parenthesized and free parenthesized expressions 10
with the operators: +, -, *, /, % (Remainder), ^ (Power), and alphanumeric operands.
4 Implement a program in C for the following Stack applications:
a. Evaluation of Suffix/Postfix expression with single digit operands and operators:
+, -, *, /, %,^.
b. Assume we have three rods (A, B, and C) and N disks of different diameters.
Initially, all the disks are on rod A, so the smaller disk is always on top of the larger
disk. The objective of the puzzle is to move all the disks to another rod (here 14
considered C), obeying the following simple rules:
i. Only one disk can be moved at a time.
ii. Each move consists of taking the topmost disk from one of the rods and
placing it on top of another rod.
No disk may be placed on top of a smaller disk.
5 Develop a C program to simulate the working of a multi-player game.
i. Each player gets n turns.
ii. Each player rolls a die during his turn. 16
iii. The number rolled by the die is added for each player.
a. At the end of n turns, the player with the maximum total wins.

6 Develop a program in C to read a polynomial of the form anxn + an-1xn-1 +an-2xn-2 +


………… + a1x + a0 (Ex: 6x4+3x3+3x2+2x+1) using a Singly Linked List (SLL).
17
Implement functions to display and evaluate the polynomial by taking the value of
‘x’ from the user.

DSATM, Bangalore-82 Page 3


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

7 Develop a program in C to create a Doubly Linked List (DLL) of Student data with
the fields: Name, USN, Sem, and CGPA supporting different operations and display 19
the status after each operation.
8 Implement a program in C to store ‘n’ integers in a Binary Search Tree (BST).
Search the BST for a given element (KEY) and display the number of accesses
24
required to find the key. Display the elements of the BST using inorder, preorder,
and postorder traversal.
9 Develop a C program to implement a road map for N Cities. Display the Depth-First
29
Search(DFS) and Breadth-First Search(BFS) traversals for the graph.
10 Develop a C program to store employee details (Employee ID: eid and Employee
Name: ename) into a hash table using a hash function H: K →L as H(K)=K mod m
32
(remainder method) where K is the Key(eid) and m is the Hash Table size.
Implement linear probing to resolve any collisions.
Open ended Programs
Consider two players - A and B. ‘N’ Pots of gold are arranged in a line, each containing some
gold coins. The players can see how many coins are in each gold pot, and each player gets turns
1 in which the player can pick the coins from a pot from either end of the line. The winner is the
player who has a higher number of coins at the end. Develop a program to solve the pots of gold
game problem.
You are given a set of n jobs where each has a deadline and profit associated with it. Each job
takes one unit of time to complete, and only one job can be scheduled at a time. We earn the
profit associated with the job if and only if the job is completed by its deadline. Find the job
scheduling of the given jobs that ensure maximum profit.
Input
2
Job id 1 2 3 4 5

deadline 2 1 2 1 3

profit 100 19 27 25 15

Develop a program to implement password encryption using a suitable data structure.


i. Store n username and encrypted passwords in a suitable data structure.
3 ii. Display the username and the encrypted password.
iii. Provide a login option to the user.
Display login success/ failure message based on the validity of the password.
Create a directed graph with n nodes. Print the distance to all reachable nodes from the given
4
source. Check if the graph is connected or not.
Assume you are using a web browser.
5
Store the URLs(links) you visited in a data structure of your choice.

DSATM, Bangalore-82 Page 4


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Implement Back/Forward Navigation such that choosing back should take the user to the
previous page and forward should take to the next page visited in the web browser.

CIE for Data Structures Laboratory (Integrated Professional Core Course (IPCC)):
This Course refers to Professional Theory Core Course Integrated with Practical Component Credit for this
course can be 03 and its Teaching Learning hours (L: T: P: PJ) can be considered as (2: 0: 2: 0).

CIE for Practical component of the PLC/PBL:


15 marks for the conduction of practical experiment and preparation of the Laboratory record, and 10 marks
for the test to be conducted after the completion of all the laboratory sessions.
On completion of every program in the laboratory, the student shall be evaluated including viva-voce and
marks shall be awarded on the same day.
Each program report can be evaluated for 15 marks (Write-up – 3 marks, Execution – 8 marks .and Viva – 4
marks)
The Laboratory test (duration 2 hours / 3 hours) after completion of all the programs shall be conducted for 50
marks and scaled down to 10 marks.
The project review (periodical review) shall be conducted for 50 marks and scale down to 10 marks.
The theory part shall be evaluated both by CIE and SEE. The practical part shall be evaluated by only CIE (no
SEE). However, questions from the practical part of PLC/PBL shall be included in the SEE question paper.
This course is common to all branches of first year B.E 2023-24 regulation.

Note: L- Theory Lecture, T- Tutorial, P-Practical, PJ-Project, CIE: Continuous Internal Evaluation, SEE:
Semester End Examination.

DSATM, Bangalore-82 Page 5


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-1
Develop a C Program to store movie Data with the fields: Title, Genre, Actor, Actress, and
rating in an appropriate data structure.

#include<stdio.h>
struct movie
{
char title[15];
char genre[15];
char actor[15];
char actress[15];
float rating;
};
void main()
{
struct movie m[10];
int n,i;
printf("Enter number of movies: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details for movie %d\n",i+1);
printf("Enter title:");
scanf("%s",m[i].title);
printf("Enter genre:");
scanf("%s",m[i].genre);
printf("Enter actor:");
scanf("%s",m[i].actor);
printf("Enter actress:");
scanf("%s",m[i].actress);
printf("Enter rating:");
scanf("%f",&m[i].rating);
printf("\n");
}
printf("The movie details are");
for(i=0;i<n;i++)
{
printf("Movie:%d\n Title:%s\n Genre:%s\n Actor:%s\n Actress:%s\n
Rating:%f\n",i+1,m[i].title,m[i].genre,m[i].actor,m[i].actress,m[i].rating);
printf("\n");
}
}
Sample Output:
enter number of movies: 2

DSATM, Bangalore-82 Page 6


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Enter details for movie 1


Enter title: abcd
Enter genre: dance
Enter actor: varun
Enter actress: shraddha
Enter rating: 4.8

Enter details for movie 2


Enter title abcd2
Enter genre dance
Enter actor punith
Enter actress shraddha
Enter rating 5
The movie details are
Movie:1
Title:abcd
Genre:dance
Actor:varun
Actress:shraddha
Rating:4.800000

Movie:2
Title:abcd2
Genre:dance
Actor:punith
Actress:shraddha
Rating:5.000000

DSATM, Bangalore-82 Page 7


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-2
Given a mathematical expression exp, write a program to examine whether the parentheses
in the expression are balanced.

#include<stdio.h>
#define MAX 10
char stack[MAX];
int top=-1;
void push(char symbol)
{
top++;
stack[top]=symbol;
}
char check_balance(char symbol)
{
char popped;
if((stack[top]=='(' && symbol==')')||(stack[top]=='{' && symbol=='}')||(stack[top]=='['
&& symbol==']'))
{
popped= stack[top--];
return popped;
}
else
return '0';
}
void main()
{
char exp[15],sym;
int i;
printf(“Enter a mathematical Expression: ”);
scanf("%s", exp);

DSATM, Bangalore-82 Page 8


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

for(i=0; exp[i]!='\0';i++)
{
if(exp[i]=='{'|| exp[i]=='('|| exp[i]=='[')
push(exp[i]);
else if(exp[i]=='}'|| exp[i]==')'|| exp[i]==']')
{
sym=check_balance(exp[i]);
if(sym=='0')
break;
}
else;
}
if(top==-1 && sym!='0')
printf("Parentheses are balanced\n");
else
printf("Parentheses are not balanced\n");
}

Sample Output
Enter a mathematical Expression: ))(({}
Parentheses are not balanced
Enter a mathematical Expression: ({}[])
Parentheses are balanced

DSATM, Bangalore-82 Page 9


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-3
Implement a program in C to convert an Infix Expression to a Postfix Expression. The
program should support both parenthesized and free parenthesized expressions with the
operators: +, -, *, /, % (Remainder), ^ (Power), and alphanumeric operands

#include <ctype.h>
#include <stdio.h>
#define SIZE 50
char s[SIZE];
int top = -1; /* Global declarations */
void push(char elem) /* Function for PUSH operation */
{
s[++top] = elem;
}

char pop() /* Function for POP operation */


{
return (s[top--]);
}

int pr(char elem) /* Function for precedence */


{
switch(elem)
{
case '#': return 0;
case '+':
case '-': return 1;
case '*':
case '/': return 2;
case '%':
case '^': return 3;
case '(' : return -1;

DSATM, Bangalore-82 Page 10


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

}
}

void main() /* Main Program */


{
char infix[50], postfix[50], symbol, elem;
int i = 0, k = 0;
printf("\n\nRead the Infix Expression ? ");
scanf("%s", infix);
push('#');
for (i=0;infix[i]!= '\0';i++)
{
symbol = infix[i];
if (symbol == '(')
push(symbol);
else if (isalnum(symbol))
postfix[k++] = symbol;
else if (symbol == ')')
{
while (s[top] != '(')
postfix[k++] = pop();
elem = pop(); /* Remove ( */
}
else /* Operator */
{
while (pr(s[top]) >= pr(symbol))
if(symbol!= '^' && s[top]!='^')
postfix[k++] = pop();
push(symbol);
}
}
/* Pop from stack till empty */

DSATM, Bangalore-82 Page 11


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

while (s[top] != '#')


postfix[k++] = pop();
postfix[k] = '\0'; /* Make pofx as valid string */
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infix, postfix);
}

Solution 2:

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

int SP(char symbol)


{
switch(symbol)
{
case '+' :
case '-': return 2;
case '*':
case '/': return 4;
case '^':
case '$': return 5;
case '(': return 0;
case '#': return -1;
default: return 8;
}
}

int IP(char symbol)


{
switch(symbol)
{

DSATM, Bangalore-82 Page 12


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

case '+':
case '-': return 1;
case '*':
case '/': return 3;
case '^':
case '$': return 6;
case '(': return 9;

case ')': return 0;

default: return 7;
}
}

void infix_postfix(char infix[], char postfix[])


{
int top, j, i;
char s[30], symbol;
top = -1;
s[++top] = '#';
j = 0;
for(i=0; i < strlen(infix); i++)
{
symbol = infix[i];
while(SP(s[top]) > IP(symbol))
{
postfix[j] = s[top--];
j++;
}
if(SP(s[top]) != IP(symbol))
s[++top] = symbol;
else
top--;

DSATM, Bangalore-82 Page 13


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

}
while(s[top] != '#')
{
postfix[j++] = s[top--];
}
postfix[j] = '\0';
}

void main()
{
char infix[20],
postfix[20];
printf("\nEnter a valid infix expression\n");
gets(infix);
infix_postfix(infix,postfix);
printf("\nThe infix expression is:\n");
printf ("%s",infix);
printf("\nThe postfix expression is:\n");
printf ("%s",postfix);
}

Sample Output:
Enter a valid infix expression (a+(b-c)*d)
The infix expression is: (a+(b-c)*d)
The postfix expression is: abc-d*+

PROGRAM-4

DSATM, Bangalore-82 Page 14


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Implement a program in C for the following Stack applications:


a. Evaluation of Suffix/Postfix expression with single digit operands and operators: +, -, *,
/, %,^.
#include<stdio.h>
#include<math.h>
#include<string.h>
double compute(char symbol, double op1, double op2)
{
switch(symbol)
{
case '+': return op1 + op2;
case' -': return op1 - op2;
case '*': return op1 * op2;
case '/': return op1 / op2;
case '$':
case '^': return pow(op1,op2);
default: return 0;

}
}
void main()
{
double s[20], res, op1, op2;
int top, i;
char postfix[20], symbol;
printf("\nEnter the postfix expression:\n");
gets(postfix);
top=-1;
for(i=0; i<strlen(postfix); i++)
{
symbol = postfix[i];
if(isdigit(symbol))

DSATM, Bangalore-82 Page 15


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

s[++top] = symbol - '0';


else
{
op2 = s[top--];
op1 = s[top--];
res = compute(symbol, op1, op2);
s[++top] = res;

}
}
res = s[top--];

printf("\nThe result is : %f\n", res);

Sample Output:
RUN1:
Enter the postfix expression: 23+
The result is: 5.000000
RUN2:
Enter the postfix expression: 23+7*
The result is: 35.000000

b. Assume we have three rods (A, B, and C) and N disks of different diameters. Initially, all
the disks are on rod A, so the smaller disk is always on top of the larger disk. The objective

DSATM, Bangalore-82 Page 16


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

of the puzzle is to move all the disks to another rod (here considered C), obeying the
following simple rules:
i. Only one disk can be moved at a time.
ii. Each move consists of taking the topmost disk from one of the rods and placing it on
top of another rod.
iii. No disk may be placed on top of a smaller disk.

#include<stdio.h>
void tower(int n, int source, int temp,int destination)
{
if(n == 0)
return;
tower(n-1, source, destination, temp);
printf("\nMove disc %d from %c to %c", n, source, destination);
tower(n-1, temp, source, destination);
}
void main()
{
int n;
printf("\nEnter the number of discs: \n");
scanf("%d", &n);
tower(n, 'A', 'B', 'C');
printf("\n\nTotal Number of moves are: %d", (int)pow(2,n)-1);
}
Sample Output:
Enter the number of discs: 3
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C
Total Number of moves are: 7

DSATM, Bangalore-82 Page 17


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-5
Develop a C program to simulate the working of a multi-player game.
i. Each player gets n turns.
ii. Each player rolls a die during his turn.
iii. The number rolled by the die is added for each player.
iv. At the end of n turns, the player with the maximum total wins.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_PLAYERS 10 // You can change this to allow more players
// Function to roll a die and return a value between 1 and 6
int rollDie() {
return (rand() % 6) + 1;
}
int main() {
int players, turns;
printf("Enter the number of players: ");
scanf("%d", &players);
printf("Enter the number of turns for each player: ");
scanf("%d", &turns);
if (players > MAX_PLAYERS || players <= 0) {
printf("Number of players must be between 1 and %d.\n", MAX_PLAYERS);
return 1;
}
int scores[MAX_PLAYERS] = {0};
for (int i = 0; i < players; i++)
{
printf("\nPlayer %d's turns:\n", i + 1);
for (int j = 0; j < turns; j++)

DSATM, Bangalore-82 Page 18


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

{
int roll = rollDie();
printf("Turn %d: Rolled a %d\n", j + 1, roll);
scores[i] += roll;
}
printf("Total score for Player %d: %d\n", i + 1, scores[i]);
}
int maxScore = scores[0], winner = 0;
for (int i = 1; i < players; i++) {
if (scores[i] > maxScore) {
maxScore = scores[i];
winner = i;
}
}
printf("\nPlayer %d wins with a total score of %d!\n", winner + 1, maxScore);
return 0;
}
Sample Output:
Enter the number of players: 3
Enter the number of turns for each player: 3
Player 1's turns:
Turn 1: Rolled a 4
Turn 2: Rolled a 6
Turn 3: Rolled a 5
Total score for Player 1: 15

Player 2's turns:


Turn 1: Rolled a 1
Turn 2: Rolled a 3

DSATM, Bangalore-82 Page 19


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Turn 3: Rolled a 1
Total score for Player 2: 5

Player 3's turns:


Turn 1: Rolled a 5
Turn 2: Rolled a 6
Turn 3: Rolled a 6
Total score for Player 3: 17

Player 3 wins with a total score of 17!

DSATM, Bangalore-82 Page 20


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM - 6
Develop a program in C to read a polynomial of the form anxn + an-1xn-1 +an-2xn-2 +
………… + a1x + a0 (Ex: 6x4+3x3+3x2+2x+1) using a Singly Linked List (SLL). Implement
functions to display and evaluate the polynomial by taking the value of ‘x’ from the user.

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

// Node structure for the polynomial (Singly Linked List)


struct Node {
int coeff; // Coefficient of the term
int exp; // Exponent of the term
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int coeff, int exp) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->coeff = coeff;
newNode->exp = exp;
newNode->next = NULL;
return newNode;
}

// Function to insert a term into the polynomial linked list


struct Node* insertTerm(struct Node* head, int coeff, int exp) {
struct Node* newNode = createNode(coeff, exp);
if (head == NULL) {
return newNode;
} else {

DSATM, Bangalore-82 Page 21


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

struct Node* temp = head;


while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
return head;
}

// Function to create the polynomial


struct Node* createPolynomial() {
struct Node* poly = NULL;
int n, coeff, exp;
printf("Enter the number of terms in the polynomial: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter coefficient and exponent for term %d: ", i + 1);
scanf("%d %d", &coeff, &exp);
poly = insertTerm(poly, coeff, exp);
}
return poly;
}

// Function to display the polynomial


void displayPolynomial(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%dx^%d", temp->coeff, temp->exp);
if (temp->next != NULL && temp->next->coeff >= 0) {
printf(" + ");

DSATM, Bangalore-82 Page 22


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

}
temp = temp->next;
}
printf("\n");
}

// Function to evaluate the polynomial for a given value of x


int evaluatePolynomial(struct Node* head, int x) {
int result = 0;
struct Node* temp = head;
while (temp != NULL) {
result += temp->coeff * pow(x, temp->exp);
temp = temp->next;
}
return result;
}

int main() {
struct Node* poly = createPolynomial();
printf("\nThe polynomial is: ");
displayPolynomial(poly);
int x;
printf("\nEnter the value of x to evaluate the polynomial: ");
scanf("%d", &x);
int result = evaluatePolynomial(poly, x);
printf("\nThe result of the polynomial evaluation is: %d\n", result);
return 0;
}

DSATM, Bangalore-82 Page 23


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Sample Output:
Enter the number of terms in the polynomial: 5
Enter coefficient and exponent for term 1: 6 4
Enter coefficient and exponent for term 2: 3 3
Enter coefficient and exponent for term 3: 3 2
Enter coefficient and exponent for term 4: 2 1
Enter coefficient and exponent for term 5: 1 0

The polynomial is: 6x^4 + 3x^3 + 3x^2 + 2x^1 + 1x^0

Enter the value of x to evaluate the polynomial: 2

The result of the polynomial evaluation is: 129

DSATM, Bangalore-82 Page 24


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-7
Develop a program in C to create a Doubly Linked List (DLL) of Student data with the
fields: Name, USN, Sem, and CGPA supporting different operations and display the status
after each operation.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define the structure for a student node
struct Student {
char name[50];
char usn[15];
int sem;
float cgpa;
struct Student* prev;
struct Student* next;
};
struct Student * first = NULL;
// Function to create a new student node
struct Student* createStudent( )
{
struct Student* newStudent = (struct Student*)malloc(sizeof(struct Student));
printf("Enter Name: ");
scanf("%s", newStudent->name);
printf("Enter USN: ");
scanf("%s", newStudent->usn);
printf("Enter Semester: ");
scanf("%d", & newStudent->sem);
printf("Enter CGPA: ");
scanf("%f", & newStudent->cgpa);

DSATM, Bangalore-82 Page 25


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

newStudent->prev = NULL;
newStudent->next = NULL;
return newStudent;
}
// Function to insert a student at the beginning of the list
void insertAtBeginning( ) {
struct Student* newStudent = createStudent( );
if (first == NULL)
{
first = newStudent;
}
else {
newStudent->next = first;
first->prev = newStudent;
first = newStudent;
}
}
// Function to insert a student at the end of the list
void insertAtEnd( )
{
struct Student* newStudent = createStudent();
if (first == NULL) {
first = newStudent;
} else {
struct Student* temp = first;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newStudent;

DSATM, Bangalore-82 Page 26


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

newStudent->prev = temp;
}
}
// Function to delete a student node by USN
struct Student* deleteByUSN(char usn[]) {
if (first == NULL) {
printf("List is empty, nothing to delete.\n");
return;
}
struct Student* temp = first;
while (temp != NULL && strcmp(temp->usn, usn) != 0) {
temp = temp->next;
}
if (temp == NULL) {
printf("Student with USN %s not found.\n", usn);
return;
}
if (temp->prev != NULL)
temp->prev->next = temp->next;
else
first = temp->next; // If deleting the first node
if (temp->next != NULL)
temp->next->prev = temp->prev;
free(temp);
printf("Student with USN %s deleted.\n", usn);
}
// Function to display the list of students
void displayList()
{

DSATM, Bangalore-82 Page 27


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

if (first == NULL)
{
printf("The list is empty.\n");
return;
}
printf("\nStudent List:\n");
struct Student* temp = first;
while (temp != NULL) {
printf("Name: %s, USN: %s, Sem: %d, CGPA: %.2f\n", temp->name, temp->usn, temp-
>sem, temp->cgpa);
temp = temp->next;
}
}
int main() {
int choice, sem;
float cgpa;
char name[50], usn[15];
do {
printf("\nDoubly Linked List Operations:\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Delete by USN\n");
printf("4. Display List\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
insertAtBeginning( );

DSATM, Bangalore-82 Page 28


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

displayList( );
break;
case 2:
insertAtEnd( );
displayList( );
break;
case 3:
printf("Enter the USN of the student to delete: ");
scanf("%s", usn);
deleteByUSN(usn);
displayList();
break;
case 4:
displayList( );
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 5);
return 0;
}

Sample Output:
Doubly Linked List Operations:
1. Insert at Beginning
2. Insert at End

DSATM, Bangalore-82 Page 29


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

3. Delete by USN
4. Display List
5. Exit
Enter your choice: 1
Enter Name: kumar
Enter USN: 1DT23IS001
Enter Semester: 3
Enter CGPA: 9.0

Student List:
Name: kumar, USN: 1DT23IS001, Sem: 3, CGPA: 9.00

Doubly Linked List Operations:


1. Insert at Beginning
2. Insert at End
3. Delete by USN
4. Display List
5. Exit
Enter your choice: 1
Enter Name: Vinay
Enter USN: 1DT23IS002
Enter Semester: 3
Enter CGPA: 9.5

Student List:
Name: Vinay, USN: 1DT23IS002, Sem: 3, CGPA: 9.50
Name: kumar, USN: 1DT23IS001, Sem: 3, CGPA: 9.00

Doubly Linked List Operations:

DSATM, Bangalore-82 Page 30


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

1. Insert at Beginning
2. Insert at End
3. Delete by USN
4. Display List
5. Exit
Enter your choice: 2
Enter Name: Kalyan
Enter USN: 1DT23IS003
Enter Semester: 3
Enter CGPA: 8.5

Student List:
Name: Vinay, USN: 1DT23IS002, Sem: 3, CGPA: 9.50
Name: kumar, USN: 1DT23IS001, Sem: 3, CGPA: 9.00
Name: Kalyan, USN: 1DT23IS003, Sem: 3, CGPA: 8.50

Doubly Linked List Operations:


1. Insert at Beginning
2. Insert at End
3. Delete by USN
4. Display List
5. Exit
Enter your choice: 1
Enter Name: Sowmya
Enter USN: 1DT23IS004
Enter Semester: 3
Enter CGPA: 7.5
Student List:
Name: Sowmya, USN: 1DT23IS004, Sem: 3, CGPA: 7.50

DSATM, Bangalore-82 Page 31


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Name: Vinay, USN: 1DT23IS002, Sem: 3, CGPA: 9.50


Name: kumar, USN: 1DT23IS001, Sem: 3, CGPA: 9.00
Name: Kalyan, USN: 1DT23IS003, Sem: 3, CGPA: 8.50

Doubly Linked List Operations:


1. Insert at Beginning
2. Insert at End
3. Delete by USN
4. Display List
5. Exit
Enter your choice: 2
Enter Name: Shyla
Enter USN: 1DT23IS005
Enter Semester: 3
Enter CGPA: 7.2

Student List:
Name: Sowmya, USN: 1DT23IS004, Sem: 3, CGPA: 7.50
Name: Vinay, USN: 1DT23IS002, Sem: 3, CGPA: 9.50
Name: kumar, USN: 1DT23IS001, Sem: 3, CGPA: 9.00
Name: Kalyan, USN: 1DT23IS003, Sem: 3, CGPA: 8.50
Name: Shyla, USN: 1DT23IS005, Sem: 3, CGPA: 7.20

Doubly Linked List Operations:


1. Insert at Beginning
2. Insert at End
3. Delete by USN
4. Display List
5. Exit

DSATM, Bangalore-82 Page 32


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Enter your choice: 4

Student List:
Name: Sowmya, USN: 1DT23IS004, Sem: 3, CGPA: 7.50
Name: Vinay, USN: 1DT23IS002, Sem: 3, CGPA: 9.50
Name: kumar, USN: 1DT23IS001, Sem: 3, CGPA: 9.00
Name: Kalyan, USN: 1DT23IS003, Sem: 3, CGPA: 8.50
Name: Shyla, USN: 1DT23IS005, Sem: 3, CGPA: 7.20

Doubly Linked List Operations:


1. Insert at Beginning
2. Insert at End
3. Delete by USN
4. Display List
5. Exit

Enter your choice: 3


Enter the USN of the student to delete: 1DT23IS001
Student with USN 1DT23IS001 deleted.

Student List:
Name: Sowmya, USN: 1DT23IS004, Sem: 3, CGPA: 7.50
Name: Vinay, USN: 1DT23IS002, Sem: 3, CGPA: 9.50
Name: Kalyan, USN: 1DT23IS003, Sem: 3, CGPA: 8.50
Name: Shyla, USN: 1DT23IS005, Sem: 3, CGPA: 7.20

Doubly Linked List Operations:


1. Insert at Beginning
2. Insert at End

DSATM, Bangalore-82 Page 33


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

3. Delete by USN
4. Display List
5. Exit
Enter your choice: 5
Exiting...

DSATM, Bangalore-82 Page 34


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-8

Implement a program in C to store ‘n’ integers in a Binary Search Tree (BST). Search the
BST for a given element (KEY) and display the number of accesses required to find the
key. Display the elements of the BST using inorder, preorder, and postorder traversal.

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

// Structure representing a node of the BST


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a node in the BST


struct Node* insertNode(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);

DSATM, Bangalore-82 Page 35


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

} else if (data > root->data) {


root->right = insertNode(root->right, data);
}
return root;
}

// Function to search a key in the BST and return the number of accesses
int searchBST(struct Node* root, int key, int* accesses) {
*accesses = 0;
struct Node* current = root;
while (current != NULL) {
(*accesses)++;
if (key == current->data) {
return 1; // Key found
}
if (key < current->data) {
current = current->left;
} else {
current = current->right;
}
}
return 0; // Key not found
}

// Function to perform inorder traversal


void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);

DSATM, Bangalore-82 Page 36


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

}
}

// Function to perform preorder traversal


void preorderTraversal(struct Node* root) {
if (root != NULL) {
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}

// Function to perform postorder traversal


void postorderTraversal(struct Node* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
}

int main() {
struct Node* root = NULL;
int n, i, element, key, accesses;
// Input: number of elements to insert into the BST
printf("Enter the number of elements to insert in the BST: ");
scanf("%d", &n);
// Inserting 'n' elements into the BST
for (i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);

DSATM, Bangalore-82 Page 37


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

scanf("%d", &element);
root = insertNode(root, element);
}
// Traversals of the BST
printf("\nInorder Traversal: ");
inorderTraversal(root);
printf("\nPreorder Traversal: ");
preorderTraversal(root);
printf("\nPostorder Traversal: ");
postorderTraversal(root);
// Search for a key in the BST
printf("\n\nEnter the key to search in the BST: ");
scanf("%d", &key);
if (searchBST(root, key, &accesses)) {
printf("Key found in %d accesses.\n", accesses);
} else {
printf("Key not found after %d accesses.\n", accesses);
}
return 0;
}

Sample Output:
Enter the number of elements to insert in the BST: 5
Enter element 1: 50
Enter element 2: 30
Enter element 3: 70
Enter element 4: 20
Enter element 5: 40

Inorder Traversal: 20 30 40 50 70

DSATM, Bangalore-82 Page 38


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Preorder Traversal: 50 30 20 40 70
Postorder Traversal: 20 40 30 70 50

Enter the key to search in the BST: 40


Key found in 3 accesses.

DSATM, Bangalore-82 Page 39


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-9
Develop a C program to implement a road map for N Cities. Display the Depth-First
Search(DFS) and Breadth-First Search(BFS) traversals for the graph.

#include<stdio.h>
int a[10][10], n, m, i, j, source, s[10], vis[10], visited[10], count;

void create()
{
printf("\nEnter the number of vertices of the digraph: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix of the graph:\n");
for(i=1; i<=n; i++)
{
vis[i]=0;
visited[i]=0;
for(j=1; j<=n; j++)
scanf("%d", &a[i][j]);
}
}

void bfs()
{
int q[10], u, front=0, rear=-1;

printf("\n Enter the source vertex: ");


scanf("%d", &source);
q[++rear] = source;
visited[source] = 1;

printf("\nThe reachable vertices are: ");


while(front<=rear)

DSATM, Bangalore-82 Page 40


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

{
u = q[front++];
for(i=1; i<=n; i++)
{
if(a[u][i] == 1 && visited[i] == 0)
{
q[++rear] = i;
visited[i] = 1; printf("\n%d", i);
}
}
}
}

void dfs(int i)
{

int j;
vis[i] = 1;
for(j=1; j<=n; j++)
if(a[i][j] == 1 && vis[j] == 0)
{
printf("\t %d",i);
dfs(j);
}
}

void main()
{

int ch;
while(1)

DSATM, Bangalore-82 Page 41


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

{
printf("\n1.Create\n2.BFS\n3.DFS\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: create();
break;
case 2: bfs();
break;
case 3: printf("\n Enter the source vertex: ");
scanf("%d", &source);
printf("\nThe reachable vertices are: ");
dfs(source);
break;
default: exit(0);
}
}
}

Sample Output:

1.Create
2.BFS
3.DFS
4.Exit
Enter your choice:1
Enter the number of vertices of the digraph: 5
Enter the adjacency matrix of the graph:
01001
00110
00000

DSATM, Bangalore-82 Page 42


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

00000
00000
1.Create
2.BFS
3.DFS
4.Exit
Enter your choice:2
Enter the source vertex:1
The reachable vertices are:
2 5 3 4
1.Create
2.BFS
3.DFS
4.Exit
Enter your choice:3
Enter the source vertex:1
The reachable vertices are:
2 3 4 5

DSATM, Bangalore-82 Page 43


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

PROGRAM-10
Develop a C program to store employee details (Employee ID: eid and Employee Name:
ename) into a hash table using a hash function H: K →L as H(K)=K mod m (remainder
method) where K is the Key(eid) and m is the Hash Table size. Implement linear probing to
resolve any collisions.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define M 3

struct employee
{
int flag;
int eid;
char ename[15];
};

struct employee emp[M];

int hash(int key)


{
int index;
index=key%M;
return index;
}

int linear_prob(int addr)


{
int i=(addr+1)%M;
while(i!=addr)
{

DSATM, Bangalore-82 Page 44


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

if(emp[i].flag!= -1)
i=(i++)%M;
else
break;
}
if(i!=addr)
return i;
else
return -1;
}

void insert()
{
int id,addr;
char name[15];
printf("\nEnter emp id: ");
scanf("%d",&id);
printf("\nEnter emp name: ");
scanf("%s",name);
addr=hash(id);
printf("addr=%d",addr);
if(emp[addr].flag==-1)
{
emp[addr].eid=id;
emp[addr].flag=1;
strcpy(emp[addr].ename,name);
}
else
{
printf("\nCollision detected..");
addr=linear_prob(addr);
if(addr!=-1)

DSATM, Bangalore-82 Page 45


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

{
emp[addr].eid=id;
emp[addr].flag=1;
strcpy(emp[addr].ename,name);
}
else
{
printf("\nHash Table is full.. Cannot insert");
return;
}
}
}

void display()
{
int i;
printf("\nThe hash table is:\n");
printf("\nHTKey\tEmpID\tEmpName");
for(i=0;i<M;i++)
{
if(emp[i].flag!=-1)
{
printf("\n%d\t%d\t%s",i,emp[i].eid,emp[i].ename);
continue;
}
}

void main()
{
int i,ch;

DSATM, Bangalore-82 Page 46


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

printf("\nCollision handling by linear probing");


for(i=0;i<M;i++)
{
emp[i].flag = -1;
}
for(;;)
{
printf("\n1.Insert\n2.Display\n");
printf("Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: insert();
break;
case 2: display();
break;
default: exit(0);
}
}
}

SAMPLE OUTPUT:
Collision handling by linear probing Enter emp id: 3
1. Insert Enter emp name: jkl

2.Display addr=0
Collision detected..

Enter your choice: 1


Enter emp id: 123 Enter your choice: 1

Enter emp name: xyz Enter emp id: 2

addr=0 Enter emp name: pqr


addr=2

Enter your choice: 1

DSATM, Bangalore-82 Page 47


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

Enter your choice: 1


Enter emp id: 2 Enter your choice: 2
Enter emp name: abc The hash table is:
addr=2 HTKey EmpID EmpName
Collision detected.. 0 123 xyz
Hash Table is full.. Cannot insert
1 3 jkl 2 2 pqr

DSATM, Bangalore-82 Page 48


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

VIVA QUESTIONS

1. What is a Register?

Ans- A register is a small amount of memory within the CPU that is used to temporarily store
instructions and data.

2. An _________ data type is a keyword of a programming language that specifies the


amount of memory needed to store data and the kind of data that will be stored in that
memory location?

Ans-abstract

3.What is the different Abstract Data Type Groups?

Integer, Floating-Type, Character & Boolean are the four different data type groups
Explanation: You determine the amount of memory to reserve by determining the appropriate
abstract data type group to use and then deciding which abstract data type within the group is
right for the data. The different abstract data type groups are Integer, Floating-Type,
Character & Boolean

4.Which of the following abstract data types are NOT used by Integer Abstract Data
type group?

A) Short
B) Int
C) float
D) long
Explanation: The integer abstract data type group consists of four abstract data types used to
reserve memory to store whole numbers: byte, short, int , and long

5.What pointer type is used to implement the heterogeneous linked list in C?

The answer is the void pointer. The heterogeneous linked list contains different data types in
it's nodes and we need a link, pointer, to connect them. Since we can't use ordinary pointers
for this, we use the void pointer. Void pointer is a generic pointer type, and capable of storing
pointer to any type.

6.What is the minimum number of queues needed to implement the priority queue?

Two. One queue is used for the actual storing of data, and the other one is used for storing the
priorities.

7.Which data structure is used to perform recursion?

The answer is Stack. Stack has the LIFO (Last In First Out) property; it remembers it's

DSATM, Bangalore-82 Page 49


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

‘caller’. Therefore, it knows to whom it should return when the function has to return. On the
other hand, recursion makes use of the system stack for storing the return addresses of the
function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even when
such equivalent iterative procedures are written explicit, stack is to be used.

8. What are some of the applications for the tree data structure?

1- Manipulation of the arithmetic expressions.


2- Symbol table construction.
3- Syntax analysis.

9. Which data structures algorithm used in solving the eight Queens problem?

Backtracking

10.In an AVL tree, at what condition the balancing is to be done?

If the "pivotal value", or the "height factor", is greater than one or less than minus one.

11. There are 8, 15, 13, and 14 nodes in four different trees. Which one of them can form
a full binary tree?

The answer is the tree with 15 nodes. In general, there are 2^n-1 nodes in a full binary tree.
By the method of elimination:
Full binary trees contain odd number of nodes, so there cannot be full binary trees with 8 or
14 nodes. Moreover, with 13 nodes you can form a complete binary tree but not a full binary
tree. Thus, the correct answer is 15.

12. What is data structure?


Answer: A data structure is a way of organizing data that considers not only the items
stored, but also their relationship to each other. Advance knowledge about the
relationship between data items allows designing of efficient algorithms for the
manipulation of data.

13. List out the areas in which data structures are applied extensively?
Answer: The names of areas are:
a. Compiler Design,
b. Operating System,
c. Database Management System,
d. Statistical analysis package,
e. Numerical Analysis,
f. Graphics,
g. Artificial Intelligence,
h. Simulation

DSATM, Bangalore-82 Page 50


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

14. What are the major data structures used in the following areas: RDBMS,
Network data model & Hierarchical data model.
The major data structures used are as follows:
a. RDBMS - Array (i.e. Array of structures)
b. Network data model - Graph
c. Hierarchical data model - Trees
d.
15. If you are using C language to implement the heterogeneous linked list, what
pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a
link, pointer to connect them. It is not possible to use ordinary pointers for this. So we
go for void pointer. Void pointer is capable of storing pointer to any type as it is a
generic pointer type.

16. Minimum number of queues needed to implement the priority queue?


Two. One queue is used for actual storing of data and another for storing priorities.

17. What is the data structures used to perform recursion?


Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so
knows whom to return when the function has to return. Recursion makes use of
system stack for storing the return addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even
when such equivalent iterative procedures are written, explicit stack is to be used.

18. What are the notations used in Evaluation of Arithmetic Expressions using
prefix and postfix forms?
Polish and Reverse Polish notations.

19. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and


Postfix notations.
Prefix Notation: ^ - * +ABC - DE + FG
Postfix Notation: AB + C * DE - - FG + ^

20. How many null branches are there in a binary tree with 20 nodes?
Answer: 21
Let us take a tree with 5 nodes (n=5)

DSATM, Bangalore-82 Page 51


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

It will have only 6 (ie,5+1) null branches.


A binary tree with n nodes has exactly n+1 null nodes.

21. What are the methods available in storing sequential files?


Answer: The methods available in storing sequential files are:
 Straight merging,
 Natural merging,
 Polyphase sort,
 Distribution of Initial runs.

22. How many different trees are possible with 10 nodes ?


Answer: 1014
For example, consider a tree with 3 nodes(n=3), it will have the maximum combination of 5
different (ie, 23 - 3 = 5) trees.

i ii iii iv v
In general:
If there are n nodes, there exist 2n-n different trees.

23. List out few of the Application of tree data-structure?


Answer: The list is as follows:
 The manipulation of Arithmetic expression,
 Symbol Table construction,
 Syntax analysis.

24. List out few of the applications that make use of Multilinked Structures?
Answer: The applications are listed below:
 Sparse matrix,
 Index generation.

DSATM, Bangalore-82 Page 52


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

25. In tree construction which is the suitable efficient data structure?


Answer: Linked list is the efficient data structure.

26. What is the type of the algorithm used in solving the 8 Queens problem?
Answer: Backtracking

27. In an AVL tree, at what condition the balancing is to be done?


Answer: If the 'pivotal value' (or the 'Height factor') is greater than 1 or less than -1.

28. What is the bucket size, when the overlapping and collision occur at same time?
Answer: One. If there is only one entry possible in the bucket, when the collision occurs,
there is no way to accommodate the colliding value. This results in the overlapping of values.

29. Traverse the given tree using Inorder, Preorder and Postorder traversals.

Answer:
 Inorder : D H B E A F C I G J
 Preorder: A B D H E C F G I J
 Postorder: H D E B F I J G C A

30. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them could
have formed a full binary tree?
Answer: 15.
In general:
There are 2n-1 nodes in a full binary tree.
By the method of elimination:
Full binary trees contain odd number of nodes. So there cannot be full binary trees with 8 or

DSATM, Bangalore-82 Page 53


DATA STRUCTURES AND APPLICATIONS LABORATORY 23ISEN32

14 nodes, so rejected. With 13 nodes you can form a complete binary tree but not a full
binary tree. So the correct answer is 15.

31. In the given binary tree, using array you can store the node 4 at which location?

Answer: At location 6

1 2 3 - - 4 - - 5

Root LC1 RC1 LC2 RC2 LC3 RC3 LC4 RC4

where LCn means Left Child of node n and RCn means Right Child of node n

DSATM, Bangalore-82 Page 54

You might also like