0% found this document useful (0 votes)
9 views59 pages

DSA Programs

Uploaded by

dr.sridevigm
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)
9 views59 pages

DSA Programs

Uploaded by

dr.sridevigm
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/ 59

Data Structures Laboratory BCSCB32

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>

int a[10], n, elem, i, pos;


void create() //creating an array
{
printf("\nEnter the number of the array elements: ");
scanf("%d", &n);
printf("\nEnter the elements for the array:\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
}//end of create()
void display() //displaying array elements
{
int i;
printf("\nThe array elements are:\n");
for(i=0; i<n; i++)
{
printf("%d\t", a[i]);
}
}//end of display()
void insert() //inserting an element into an array
{
printf("\nEnter the position for the new element: ");
scanf("%d", &pos);
printf("\nEnter the element to be inserted: ");
scanf("%d", &elem);
for(i=n-1; i>=pos; i--)
{

DSATM, Bangalore-82 Page 1


Data Structures Laboratory BCSCB32

a[i+1] = a[i];
}
a[pos] = elem;
n = n+1;
}//end of insert()
void del() //deleting an array element
{
printf("\nEnter the position of the element to be deleted: ");
scanf("%d", &pos);
elem = a[pos];
for(i=pos; i<n-1; i++)
{
a[i] = a[i+1];
}
n = n-1;
printf("\nThe deleted element is = %d", elem);
}//end of delete()
void main()
{
int ch;
for(;;)
{
printf("\n\n--------Menu----------- \n");
printf("1.Create\n 2.Display\n 3.Insert\n 4.Delete\n 5.Exit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: create(); break;
case 2: display(); break;
case 3: insert(); break;
case 4: del(); break;

DSATM, Bangalore-82 Page 2


Data Structures Laboratory BCSCB32

case 5: exit(0); break;


default: printf("\nInvalid choice:\n"); break;
}
}
}// end of main

SAMPLE OUTPUT:
--------Menu-----------
1.Create
2.Display
3.Insert
4.Delete
5.Exit
Enter your choice: 1
Enter the size of the array elements: 5
Enter the elements for the array:
10 20 30 40 50

--------Menu-----------
1.Create
2.Display
3.Insert
4.Delete
5.Exit
Enter your choice: 2
The array elements are:
10 20 30 40 50
--------Menu-----------
1.Create
2.Display
3.Insert
4.Delete
5.Exit
Enter your choice: 3
Enter the position for the new element: 2
Enter the element to be inserted: 90

DSATM, Bangalore-82 Page 3


Data Structures Laboratory BCSCB32

--------Menu-----------
1.Create
2.Display
3.Insert
4.Delete
5.Exit
Enter your choice: 2
The array elements are:
10 20 90 30 40 50

--------Menu-----------
1.Create
2.Display
3.Insert
4.Delete
5.Exit
Enter your choice: 4
Enter the position of the element to be deleted: 5
The deleted element is = 50

--------Menu-----------
1.Create
2.Display
3.Insert
4.Delete
5.Exit
Enter your choice: 2

The array elements are:


10 20 90 30 40
--------Menu-----------
1.Create
2.Display
3.Insert
4.Delete
5.Exit
Enter your choice: 5

DSATM, Bangalore-82 Page 4


Data Structures Laboratory BCSCB32

PROGRAM-2
Develop a C program to implement push, pop, and display operations on a STACK of
characters using functions for each. Display underflow and overflow messages
appropriately. Demonstrate how the Stack can be used to check if the parentheses are
balanced.

#include<stdio.h>

#define MAX 10
char stack[MAX], exp[10], item;
int ch, top = -1;

/*PUSH FUNCTION*/
void push(char item)
{
if (top == (MAX-1))
printf("\nStack Overflow");
else
stack[++top] = item;

}
int pop()
{
char popped;
if(top == -1)
printf("\n\n Stack Underflow");
else
{
popped = stack[top--];
printf("\n Popped element is %c", popped);
}
return popped;

DSATM, Bangalore-82 Page 5


Data Structures Laboratory BCSCB32

void display()
{
int i;
if(top == -1)
printf("\nStack is Empty");
else
{
printf("\n The stack contents are:");
for(i=top; i>=0; i--)
printf("\n | %c |", stack[i]);
printf("\n");
}
}
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()
{
for(;;)
{

DSATM, Bangalore-82 Page 6


Data Structures Laboratory BCSCB32

printf("\n\n----------MAIN MENU----------\n");
printf("1. PUSH (Insert) into the Stack\n ");
printf("2. POP (Delete) from the Stack\n ");
printf("3. DISPLAY the Stack Contents\n ");
printf("4. CHECK parentheses \n ");
printf("5. EXIT (End the Execution) \n ");
printf("\nEnter Your Choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\n Enter an element to be pushed: ");
scanf("%d", &item);
push(item);
break;
case 2: item=pop( );
break;
case 3: display();
break;
case 4: printf(“Enter a mathematical Expression: ”);
scanf("%s", exp);
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;

DSATM, Bangalore-82 Page 7


Data Structures Laboratory BCSCB32

}
if(top==-1 && sym!='0')
printf("Parentheses are balanced\n");
else
printf("Parentheses are not balanced\n");
break;
case 5: exit(0);
default:printf("\n INVALID CHOICE.!!!! TRY AGAIN");
}//end switch
}
}

SAMPLE OUTPUT
----------MAIN MENU---------- ----MAIN MENU----
1. PUSH (Insert) into the Stack 1. PUSH (Insert) in the Stack
2. POP (Delete) from the Stack 2. POP (Delete) from the Stack
3. DISPLAY the Stack Contents 3. EXIT (End the Execution)
4. CHECK parentheses Enter Your Choice: 1
5. EXIT (End the Execution) Enter an element to be pushed: 9
Enter Your Choice: 1 Stack is Overflow
Enter an element to be pushed: 1 The stack contents are:
The stack contents are: 1 1
2
----------MAIN MENU---------- 2
1. PUSH (Insert) into the Stack 1
2. POP (Delete) from the Stack
3. DISPLAY the Stack Contents ----MAIN MENU----
4. CHECK parentheses 1. PUSH (Insert) in the Stack
5. EXIT (End the Execution) 2. POP (Delete) from the Stack
Enter Your Choice: 1 3. EXIT (End the Execution)
Enter an element to be pushed: 2 Enter Your Choice: 2
Popped element is 1

AFTER PUSH OPERATION FOR 4 TIMES The stack contents are:

DSATM, Bangalore-82 Page 8


Data Structures Laboratory BCSCB32

2 Stack is Empty
2 ----MAIN MENU----
1 1. PUSH (Insert) in the Stack

AFTER POP OPERATION FOR 4 TIMES


(-------- 2. POP (Delete) from the Stack

----MAIN MENU---- 3. EXIT (End the Execution)

1. PUSH (Insert) in the Stack Enter Your Choice: 3

2. POP (Delete) from the Stack


3. EXIT (End the Execution) Enter a mathematical Expression: ))(({}
Enter Your Choice: 2 Parentheses are not balanced
Stack is Underflow Enter a mathematical Expression: ({}[])
The stack contents are:
Parentheses are balanced

DSATM, Bangalore-82 Page 9


Data Structures Laboratory BCSCB32

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 Laboratory BCSCB32

}
}

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

DSATM, Bangalore-82 Page 11


Data Structures Laboratory BCSCB32

/* Pop from stack till empty */


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 Laboratory BCSCB32

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 Laboratory BCSCB32

}
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*+

DSATM, Bangalore-82 Page 14


Data Structures Laboratory BCSCB32

PROGRAM-4
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; <strlen(postfix); i++)
{

DSATM, Bangalore-82 Page 15


Data Structures Laboratory BCSCB32

symbol = postfix[i];
if(isdigit(symbol))
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

DSATM, Bangalore-82 Page 16


Data Structures Laboratory BCSCB32

b. Solving Tower of Hanoi problem with n disks


#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 Laboratory BCSCB32

PROGRAM-5
Develop a menu-driven program in C to implement insertion, deletion, and display
operations on a linear queue of integers using functions for each operation. Demonstrate
Overflow and Underflow situations.

#include <stdio.h>
#define MAX 3
int queue_array[MAX];
int rear = - 1;
int front = 0;

void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
printf("Insert the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */

void delete()
{
if (front > rear)
{
printf("Queue Underflow \n");
return ;
}

DSATM, Bangalore-82 Page 18


Data Structures Laboratory BCSCB32

else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */

void display()
{
int i;
if (front > rear)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d \t ", queue_array[i]);
printf("\n");
}
} /* End of display() */
void main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);

DSATM, Bangalore-82 Page 19


Data Structures Laboratory BCSCB32

switch (choice)
{
case 1: insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(1);
default: printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */

SAMPLE OUTPUT:
1.Insert element to queue 4.Quit
2.Delete element from queue Enter your choice : 1
3.Display all elements of queue Insert the element in queue : 20
4.Quit 1.Insert element to queue
Enter your choice : 2 2.Delete element from queue
Queue Underflow 3.Display all elements of queue
1.Insert element to queue 4.Quit
2.Delete element from queue Enter your choice : 1
3.Display all elements of queue Insert the element in queue : 30
4.Quit 1.Insert element to queue
Enter your choice : 1 2.Delete element from queue
Insert the element in queue : 10 3.Display all elements of queue
1.Insert element to queue 4.Quit
2.Delete element from queue Enter your choice : 1
3.Display all elements of queue Queue Overflow

DSATM, Bangalore-82 Page 20


Data Structures Laboratory BCSCB32

1.Insert element to queue 1.Insert element to queue


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

DSATM, Bangalore-82 Page 21


Data Structures Laboratory BCSCB32

PROGRAM - 6
Develop a program to simulate the working of a printer using a Circular Queue(CQ) of
characters with functions for insertion, deletion, and display operations.
#include <stdio.h>
#define MAX 3
char cq[MAX];
int rear = - 1, front = 0, count=0;

void insert()
{
int add_item;
if (count==MAX)
printf("Queue Overflow \n");
else
{
printf("Insert the element to printer queue : ");
scanf("%c", &add_item);
rear = (rear + 1)%MAX;
cq[rear] = add_item;
count++;
}
} /* End of insert() */

void delete()
{
if (count==0)
{
printf("Queue Underflow \n");
return ;
}
else

DSATM, Bangalore-82 Page 22


Data Structures Laboratory BCSCB32

{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = (front + 1)%MAX;
count--;
}
} /* End of delete() */

void display()
{
int i;
if (count==0)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
i = front;
for (j=1;j <= count; j++)
{
printf("Printing %c \n ", queue_array[i]);
i=(i+1)%MAX
}
printf("\n");
} /* End of display() */
void main()
{
int choice;
while (1)
{
printf("1.Insert element to printer queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");

DSATM, Bangalore-82 Page 23


Data Structures Laboratory BCSCB32

printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1: insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(1);
default: printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */

SAMPLE OUTPUT:
1. Insert element to printer queue
2.Delete element from queue 1. Insert element to printer queue
3.Display all elements of queue 2.Delete element from queue
4.Quit 3.Display all elements of queue
Enter your choice : 2 4.Quit
Queue Underflow Enter your choice : 1
Insert the element to printer queue: B
1. Insert element to printer queue
2.Delete element from queue 1. Insert element to printer queue
3.Display all elements of queue 2.Delete element from queue
4.Quit 3.Display all elements of queue
Enter your choice : 1 4.Quit
Insert the element to printer queue: A Enter your choice : 1

DSATM, Bangalore-82 Page 24


Data Structures Laboratory BCSCB32

Insert the element to printer queue: C 1. Insert element to printer queue


2.Delete element from queue
1. Insert element to printer queue 3.Display all elements of queue
2.Delete element from queue 4.Quit
3.Display all elements of queue Enter your choice : 2
4.Quit Element deleted from queue is : 10
Enter your choice : 1
Queue Overflow 1. Insert element to printer queue
2.Delete element from queue
1. Insert element to printer queue 3.Display all elements of queue
2.Delete element from queue 4.Quit
3.Display all elements of queue Enter your choice :1
4.Quit Insert the element to printer queue: D
Enter your choice : 3
Queue is : 1. Insert element to printer queue
Printing A 2.Delete element from queue
Printing B 3.Display all elements of queue
Printing C 4.Quit
Enter your choice :3
Queue is : Printing C
Printing B Printing D

DSATM, Bangalore-82 Page 25


Data Structures Laboratory BCSCB32

PROGRAM-7
Design and Develop a menu-driven program in C to read a polynomial P of the form anxn +
an1xn-1 +an-2xn-2 + ………… + a1x + a0 (Ex: 6x4+3x3+3x2+2x+1) using rear insertion in 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<math.h>
#include<alloc.h>
struct node
{
int co,ex;
struct node *link;
};
typedef struct node* poly;
poly first=NULL;
void attach(int c, int x)
{
poly temp, cur;
temp = (struct node *)malloc(sizeof(struct node));
temp->co = c;
temp->ex = x;
temp->link = NULL;
if(first==NULL)
{
first=temp;
return;
}
cur = first;
while(cur->link!= NULL)

DSATM, Bangalore-82 Page 26


Data Structures Laboratory BCSCB32

cur = cur->link;
cur->link = temp;
}
void read()
{
int ch=1;
int cf,x;
while(ch!=0)
{
printf("Enter Coeff and exponent: ");
scanf("%d%d",&cf,&x);
attach(cf,x);
printf("\n Press 1 to insert a new term otherwise press 0: ");
scanf("%d", &ch);
}
}
void display()
{
poly temp;
if(first == NULL)
{
printf("polynomial does not exist\n");
return;
}
temp =first;
while(temp!=NULL)
{
if(temp->co < 0)

DSATM, Bangalore-82 Page 27


Data Structures Laboratory BCSCB32

printf("%d x^%d ",temp->co,temp->ex);


else
printf("+%d x^%d ",temp->co,temp->ex);
temp = temp->link;
}
}

void evaluate()
{
poly temp;
int x;
int result=0;
temp=first;
printf("\nEnter value of x to evaluate:\n");
scanf("%d", &x);
while(temp!= NULL)
{
result = result +temp->co*pow(x,temp->ex);
temp=temp->link;
}
printf("\nPolynomial result is: %d", result);
}
void main()
{
int ch;
first->link = NULL;
printf("Enter the polynomial\n");
read();

DSATM, Bangalore-82 Page 28


Data Structures Laboratory BCSCB32

evaluate(eval);
}
SAMPLE OUTPUT:
Enter the polynomial
Enter Coeff and 3 exponents: 6 2
If you wish to continue press 1 otherwise press 0:1
Enter Coeff and 3 exponents: -4 0
If you wish to continue press 1 otherwise press 0:1
Enter Coeff and 3 exponents: 3 3
If you wish to continue press 1 otherwise press 0:1
Enter Coeff and 3 exponents: 2 1
If you wish to continue press 1 otherwise press 0:1
Enter Coeff and 3 exponents: -2 1
If you wish to continue press 1 otherwise press 0:0
Enter values of x to evaluate: 1
Polynomial result is:5

DSATM, Bangalore-82 Page 29


Data Structures Laboratory BCSCB32

PROGRAM-8

Develop a menu-driven program in C to create a Doubly Linked List (DLL) of Movie Data
with the fields: Title, Genre, Actor, Actress, and rating. Implement functions for insert at
front, Delete from front, insert at rear, and delete from rear of the DLL. Display the linked
list after each operation.

#include<stdio.h>
struct emp
{
char title[20], genre[10], actor[15], actress[10];
int rating;
struct emp *left;
struct emp *right;
};
typedef struct emp NODE;
NODE * first=NULL,*temp=NULL,*newnode=NULL;

NODE* getnode()
{
newnode=(NODE*)malloc(sizeof(NODE)); //Create first NODE
printf("\nEnter Title, Genre, Actor, Actress, and rating \n");
gets(newnode->title);
scanf("%s",newnode->genre);
scanf("%s",newnode->actor);
scanf("%s",newnode->actress);
scanf("%f",&(newnode->rating));
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}

void insert_front()

Dept. of ISE, DSATM. Page 30


Data Structures Laboratory BCSCB32

{
NODE * newnode=getnode();
newnode->right=first;
if(first!=NULL)
first->left=newnode;
first=newnode;
}

void delete_front()
{
if(first==NULL)
{
printf("Linked list is empty\n");
return;
}
temp=first;
if(first!=NULL)
first=first->right;
free(temp);
first->left=NULL;
}

void insert_rear()
{
newnode=getnode();
if(first==NULL)
first=newnode;
else
{
temp=first;
while(temp->right!=NULL)
{

Dept. of ISE, DSATM. Page 31


Data Structures Laboratory BCSCB32

temp=temp->right;
}
temp->right=newnode;
newnode->left=temp;
}
}

void delete_rear()
{
if(first==NULL)
{
printf("Linked list is empty\n");
return;
}
if(first->right==NULL)
{
free(first);
first=NULL;
return;
}
temp=first;
while(temp->right!=NULL)
{
temp=temp->right;
}
temp->left->right=NULL;
free(temp);
}

void display()
{
int count=0;

Dept. of ISE, DSATM. Page 32


Data Structures Laboratory BCSCB32

if(first == NULL)
{
printf("List is empty..! \n");
return;
}
temp=first;
printf("\n----MOVIE DATA----\n");
printf("\n Title\t Genre\t Actor \t Actress \t Rating \n");
while (temp!= NULL)
{
printf("%s\t%s\t%s\t%s\t%f\n", temp->title, temp->genre, temp->actor, temp-
>actress,temp->rating);
temp = temp->right;
count++;
}
printf(" No of Movies = %d ", count);
}

void main()
{
int ch,n,i;
while (1)
{
printf("-----------------MENU----------------------\n");
printf("\n 1–Create \n 2–Display \n 3–Insert at the rear \n 4–delete from rear");
printf("\n 5–Insert at front \n 6–delete from front \n 7–exit\n");
printf("--------------------------------------------\n");
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("\n Enter no of movies : ");

Dept. of ISE, DSATM. Page 33


Data Structures Laboratory BCSCB32

scanf("%d", &n);
for(i=0;i<n;i++)
insert_rear();
break;
case 2: display(); break;
case 3: insert_rear(); break;
case 4: delete_rear(); break;
case 5: insert_front(); break;
case 6: delete_front(); break;
case 7: exit(0);
default: printf("Invalid choice\n");
}
}
}

SAMPLE OUTPUT:
–---------------MENU---------------------- 4.2
1– Create
2 - Display Enter Title, Genre, Actor, Actress, and rating
3 - Insert at the rear Da Vinci Code
4 - deletefrom rear Mystery
5 - Insert at front Tom
6 - deletefrom front Audrey
7 -exit 4
------------------------------------------------
Enter choice : 1 Enter choice : 2
Enter no of movies : 2 ----MOVIE DATA----
Enter Title, Genre, Actor, Actress, and rating Title Genre Actor Actress rating
The holiday The holiday Romcom Jack Kate 4.2
Romcom Da Vinci Code Mystery Tom Audrey 4
Jack No of movies = 2
Kate

Dept. of ISE, DSATM. Page 34


Data Structures Laboratory BCSCB32

Enter choice : 3 Enter choice : 5


Enter Title, Genre, Actor, Actress, and rating Enter Title, Genre, Actor, Actress, and
Harry Potter rating
Fantasy Sherlock Holmes
Daniel Mystery
Emma Robert
4.5 Rachel
4.5
Enter choice : 2
----MOVIE DATA---- Enter choice : 2
Title Genre Actor Actress rating ----MOVIE DATA----
The holiday Romcom Jack Kate 4.2 Sherlock Holmes Mystery Robert Rachel 4.5
Da Vinci Code Mystery Tom Audrey 4 The holiday Romcom Jack Kate 4.2
Harry Potter Fantasy Daniel Emma 4.5 Da Vinci Code Mystery Tom Audrey 4

No of movies = 3 No of movies = 3
Enter choice : 6
Enter choice : 4

Enter choice : 2
Enter choice : 2
----MOVIE DATA----
----MOVIE DATA----
The holiday Romcom Jack Kate 4.2
Title Genre Actor Actress rating
Da Vinci Code Mystery Tom Audrey 4
The holiday Romcom Jack Kate 4.2
No of movies = 2
Da Vinci Code Mystery Tom Audrey 4
No of movies = 2
Enter choice : 7

Dept. of ISE, DSATM. Page 35


Data Structures Laboratory BCSCB32

PROGRAM-9
Develop a menu-driven program in C to create a Binary Search Tree (BST) of Integers.
Traverse the BST in Inorder, Preorder and PostOrder. Search the BST for a given element
(KEY) and display an appropriate message

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

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

typedef struct BST NODE;

NODE *root=NULL,*cur,*prev;

NODE* insert(int item)


{
NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->data = item;
temp->left = temp->right = NULL;
if (root == NULL)
{
root=temp;
return;
}
cur=root;
while(cur!=NULL)
{
prev=cur;

Dept. of ISE, DSATM. Page 36


Data Structures Laboratory BCSCB32

if (item < (cur->data))


cur=cur->left;
else if(item>(cur->data))
cur=cur->right;
else
return;
}
if (item < prev->data)
prev->left=temp;
else
prev->right=temp;
}

void search(NODE * node, int key)


{
if(node == NULL)
printf("\nElement not found");
else if(key < node->data)
{
search(node->left,key);
}
else if(key > node->data)
{
search(node->right,key);
}
else
printf("\nElement found”);
}

void inorder(NODE *node)


{
if(node != NULL)

Dept. of ISE, DSATM. Page 37


Data Structures Laboratory BCSCB32

{
inorder(node->left);
printf("%d\t", node->data);
inorder(node->right);
}
}

void preorder(NODE *node)


{
if(node != NULL)
{
printf("%d\t", node->data);
preorder(node->left);
preorder(node->right);
}
}

void postorder(NODE *node)


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

void main()
{
int item, ch, i, n;
while (1)

Dept. of ISE, DSATM. Page 38


Data Structures Laboratory BCSCB32

{
printf("\n1.Create\n2.Search\n3.Inorder\n4.Preorder\n5.Postorder\n 6.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("\nEnter no. of elements to insert\n");
scanf("%d",&n);
printf("\nEnter items to create BST\n");
for(i=0;i<n;i++)
{
scanf("%d", &item);
insert(item);
}
break;
case 2: printf("\nEnter the element to search: ");
scanf("%d", &item);

search(root, item);
break;
case 3: printf("\nInorder Traversal: \n");
inorder(root);
break;
case 4: printf("\nPreorder Traversal: \n");
preorder(root);
break;
case 5: printf("\nPostorder Traversal: \n");
postorder(root);
break;
case 6: exit(0);
default:printf("\nWrong option");
break;

Dept. of ISE, DSATM. Page 39


Data Structures Laboratory BCSCB32

}
}
}
SAMPLE OUTPUT:
1. Create
2. Search
3. Inorder
4. Preorder
5. Postorder
6. Exit
Enter your choice: 1
Enter items to create BST like(6,9,5,2,8,15,24,14,7,8,5,2)
6 9 5 2 8 15 24 14 7 8 5 2
Enter your choice: 4

Inorder Traversal:
2 5 6 7 8 9 14 15 24
Enter your choice: 5

Preorder Traversal:
6 5 2 9 8 7 15 14 24
Enter your choice: 6

Postorder Traversal:
2 5 7 8 14 24 15 9 6
Enter your choice: 2
Enter the element to search: 24
Element found
Enter your choice: 2
Enter the element to search: 50
Element not found

Dept. of ISE, DSATM. Page 40


Data Structures Laboratory BCSCB32

PROGRAM-10
Develop a menu-driven program in C to create a Maxheap of Integers. Demonstrate deletion
operation on max-heap

#include<stdio.h>
#define MAX 10
int heap[MAX],n;
void insert_heap(int item)
{
int c;
if(n==MAX-1)
{
printf("Heap is full \n");
return;
}
c=n+1;
while((c!=1) && item>heap[c/2])
{
heap[c]=heap[c/2];
c/=2;
}
heap[c]=item;
n++;
}
void del_heap()
{
int item, temp, parent, child;
if(n==0)
{
printf("Heap is empty \n");
return;

Dept. of ISE, DSATM. Page 41


Data Structures Laboratory BCSCB32

}
item= heap[1];
temp=heap[n];
parent=1;
child=2;
while(child<=n)
{
if((child<n) && (heap[child]<heap[child+1]))
child++;
if(temp>=heap[child])
break;
heap[parent]=heap[child];
parent=child;
child*=2;
}
heap[parent]=temp;
n--;
}
void display()
{
int i;
if(n==0)
{
printf("Heap is empty \n");
return;
}
for(i=1;i<=n;i++)
{
printf("%d\t",a[i]);
}
}

Dept. of ISE, DSATM. Page 42


Data Structures Laboratory BCSCB32

void main()
{
int item, ch, i, n;
while (1)
{
printf("\n1.Insert into heap \n2.Delete from heap\n3.Display \n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("\nEnter an element to insert:");
scanf("%d", &item);
insert_heap(item);
break;
case 2: del_heap();
break;
case 3: display();
break;
case 4: exit(0);
default:printf("\nWrong option"); break;
}
}
}
SAMPLE OUTPUT:
1.Insert into heap

2.Delete from heap 1.Insert into heap


2.Delete from heap
3.Display
3.Display
4.Exit 4.Exit

Enter your choice: 1 Enter your choice: 1


Enter an element to insert: 20
Enter an element to insert: 10

Dept. of ISE, DSATM. Page 43


Data Structures Laboratory BCSCB32

1.Insert into heap 1.Insert into heap


2.Delete from heap 2.Delete from heap
3.Display 3.Display
4.Exit 4.Exit
Enter your choice: 1 Enter your choice: 3
Enter an element to insert: 5 20 15 5 10

1.Insert into heap 1.Insert into heap


2.Delete from heap
2.Delete from heap
3.Display
4.Exit 3.Display

Enter your choice: 1 4.Exit


Enter an element to insert: 15
Enter your choice: 2

20 deleted

Dept. of ISE, DSATM. Page 44


Data Structures Laboratory BCSCB32

PROGRAM-11
Develop a program in C to create a Directed Graph(G) of N Cities using the Adjacency
Matrix. Print all the nodes reachable from a given starting node in the digraph using
DFS/BFS method

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

Dept. of ISE, DSATM. Page 45


Data Structures Laboratory BCSCB32

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


while(front<=rear)
{
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()
{

Dept. of ISE, DSATM. Page 46


Data Structures Laboratory BCSCB32

int ch;
while(1)

{
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 01001
2.BFS 00110
3.DFS 00000
4.Exit 00000
Enter your choice:1 00000
Enter the number of vertices of the digraph: 1.Create
5 2.BFS
Enter the adjacency matrix of the graph: 3.DFS

Dept. of ISE, DSATM. Page 47


Data Structures Laboratory BCSCB32

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

Dept. of ISE, DSATM. Page 48


Data Structures Laboratory BCSCB32

PROGRAM-12

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

Dept. of ISE, DSATM. Page 49


Data Structures Laboratory BCSCB32

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)

Dept. of ISE, DSATM. Page 50


Data Structures Laboratory BCSCB32

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

Dept. of ISE, DSATM. Page 51


Data Structures Laboratory BCSCB32

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 your choice: 1
1. Insert Enter emp id: 3
2.Display Enter emp name: jkl
addr=0

Enter your choice: 1 Collision detected..

Enter emp id: 123


Enter emp name: xyz Enter your choice: 1

addr=0 Enter emp id: 2


Enter emp name: pqr

Dept. of ISE, DSATM. Page 52


Data Structures Laboratory BCSCB32

addr=2 Hash Table is full.. Cannot insert

Enter your choice: 1 Enter your choice: 2


Enter emp id: 2 The hash table is:
Enter emp name: abc HTKey EmpID EmpName
addr=2 0 123 xyz
Collision detected..
1 3 jkl 2 2 pqr

Dept. of ISE, DSATM. Page 53


DATA STRUCTURES AND APPLICATIONS LABORATORY 23CSCB32

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 54


DATA STRUCTURES AND APPLICATIONS LABORATORY 23CSCB32

‘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 55


DATA STRUCTURES AND APPLICATIONS LABORATORY 23CSCB32

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 56


DATA STRUCTURES AND APPLICATIONS LABORATORY 23CSCB32

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 57


DATA STRUCTURES AND APPLICATIONS LABORATORY 23CSCB32

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 58


DATA STRUCTURES AND APPLICATIONS LABORATORY 23CSCB32

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 59

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy