0% found this document useful (0 votes)
14 views68 pages

RF Dslab

From my College

Uploaded by

ankithakarmanchi
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)
14 views68 pages

RF Dslab

From my College

Uploaded by

ankithakarmanchi
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/ 68

DEPARTMENT OF

ARTIFICIAL INTELLIGENCE & DATA SCIENCE

LAB MANUAL
DATA STRUCTURE LABORATORY,[BCSL305]

2023-2024

PreparedBy
Mrs. Rummana Firdaus
Assistant Professor
Laboratory Plan for odd Semester 2023-24

Semester: III Subject Name: DATA STRUCTURE LABORATORY


Subject Code: BCSL305
Name of the Faculty: Rummana Firdaus
Course Outcome:
After completion of this course, the students would be able to
CO1: Analyze various linear and non-linear data structures
CO2:Demonstrate the working nature of different types of data structures and their applications
CO3:Use appropriate searching and sorting algorithms for the give scenario.
CO4:Apply the appropriate data structure for solving real world problems

Sl Program Course
Experiments
No No. Outcomes
Develop a Program in C for the following:
a) Declare a calendar as an array of 7 elements (A dynamically Created array) to represent
7 days of a week. Each Element of the array is a structure having three fields. The first
field is the name of the Day (A dynamically allocated String), The second field is the
1 1 date of the Day (A integer), the third field is the description of the activity for a CO1,CO2
particular day (A dynamically allocated String).
b) Write functions create(), read() and display(); to create the calendar, to read the data
from the keyboard and to print weeks activity details report on screen.

Develop a Program in C for the following operations on Strings.


a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR
2 with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in CO1,CO3
2
STR.
Support the program with functions for each of the above operations. Don't use Built-in
functions.

Develop a menu driven Program in C for the following operations on STACK of Integers
(Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
3 3 d. Demonstrate Overflow and Underflow situations on Stack CO1,CO4
e. Display the status of Stack
f. Exit
Support the program with appropriate functions for each of the above operations

Develop a Program in C for converting an Infix Expression to Postfix Expression.


Program should support for both parenthesized and free parenthesized
4 4 expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric CO1,CO4
operands.

Develop a Program in C for the following Stack Applications


a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
5 5 b. Solving Tower of Hanoi problem with n disks CO1,CO4

Develop a menu driven Program in C for the following operations on Circular QUEUE of
Characters (Array Implementation of Queue with maximum size MAX)
6 6 a. Insert an Element on to Circular QUEUE CO1,CO2
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit
Support the program with appropriate functions for each of the above operations
Develop a menu driven Program in C for the following operations on Singly Linked List
(SLL) of Student Data with the fields: USN, Name, Programme, Sem,PhNo
a. Create a SLL of N Students Data by using front insertion.
7 7 b. Display the status of SLL and count the number of nodes in it CO1,CO2
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit
Develop a menu driven Program in C for the following operations on Doubly Linked List
(DLL) of Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
8 8 c. Perform Insertion and Deletion at End of DLL CO1,CO2
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue.
f. Exit

Develop a Program in C for the following operationson Singly Circular Linked List
(SCLL) with header nodes
a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
9 9 CO1,CO4
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result
in POLYSUM(x,y,z).
Support the program with appropriate functions for each of the above operations
Develop a menu driven Program in C for the following operations on Binary Search Tree
(BST) of Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
10 10 CO1,CO3
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
Develop a Program in C for the following operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
11 11 b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS CO1,CO4
method

Given a File of N employee records with a set K of Keys (4-digit) which uniquely
determine the records in file F. Assume that file F is maintained in memory by a Hash
Table (HT) of m memory locations with L as the set of memory addresses (2-digit) of
locations in HT. Let the keys in K and addresses in L are Integers. Develop a Program in C
12 12 that uses Hash function H: CO1,CO4
K →L as H(K)=K mod m (remainder method), and implement hashing
technique to map a given key K to the address space L. Resolve the collision (if any) using
linear probing.
1. Develop a Program in C for the following:
a) Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7 days of a week.
Each Element of the array is a structure having three fields. The first field is the name of the Day (A
dynamically allocated String), The second field is the date of the Day (A integer), the third field is the
description of the activity for a particular day (A dynamically allocated String).
b) Write functions create(), read() and display(); to create the calendar, to read the data from the keyboard and
to print weeks activity details report on screen.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NUM_DAYS_IN_WEEK 7
// Structure to represent a day
typedef struct
{
char *acDayName; // Dynamically allocated string for the day name
int iDate; // Date of the day
char *acActivity; // Dynamically allocated string for the activity description
}DAYTYPE;

void fnFreeCal(DAYTYPE *);


void fnDispCal(DAYTYPE *);
void fnReadCal(DAYTYPE *);
DAYTYPE *fnCreateCal();

int main()
{
// Create the calendar
DAYTYPE *weeklyCalendar = fnCreateCal();

// Read data from the keyboard


fnReadCal(weeklyCalendar);

// Display the week's activity details


fnDispCal(weeklyCalendar);

// Free allocated memory


fnFreeCal(weeklyCalendar);

return 0;
}

DAYTYPE *fnCreateCal()
{
DAYTYPE *calendar = (DAYTYPE *)malloc(NUM_DAYS_IN_WEEK * sizeof(DAYTYPE));

for(int i = 0; i< NUM_DAYS_IN_WEEK; i++)


{
calendar[i].acDayName = NULL;
calendar[i].iDate = 0;
calendar[i].acActivity = NULL;
}
3
return calendar;
}

void fnReadCal(DAYTYPE *calendar)


{
char cChoice;
for(int i = 0; i< NUM_DAYS_IN_WEEK; i++)
{
printf("Do you want to enter details for day %d [Y/N]: ", i + 1);
scanf("%c", &cChoice); getchar();

if(tolower(cChoice) == 'n')
continue;

printf("Day Name: ");


char nameBuffer[50];
scanf("%s", nameBuffer);
calendar[i].acDayName = strdup(nameBuffer); // Dynamically allocate and copy the string

printf("Date: ");
scanf("%d", &calendar[i].iDate);

printf("Activity: ");
char activityBuffer[100];
scanf(" %[^n]", activityBuffer); // Read the entire line, including spaces
calendar[i].acActivity = strdup(activityBuffer);

printf("n");
getchar(); //remove trailing enter character in input buffer
}
}

void fnDispCal(DAYTYPE *calendar)


{
printf("nWeek's Activity Details:n");
for(int i = 0; i< NUM_DAYS_IN_WEEK; i++)
{
printf("Day %d:n", i + 1);
if(calendar[i].iDate == 0)
{
printf("No Activitynn");
continue;
}

printf(" Day Name: %sn", calendar[i].acDayName);


printf(" Date: %dn", calendar[i].iDate);
printf(" Activity: %snn", calendar[i].acActivity);
}
}

void fnFreeCal(DAYTYPE *calendar)


{
for(int i = 0; i< NUM_DAYS_IN_WEEK; i++)

4
{
free(calendar[i].acDayName);
free(calendar[i].acActivity);
}
free(calendar);
}

5
2. Develop a Program in C for the following operations on Strings.
a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR with REP if PAT exists in
STR. Report suitable messages in case PAT does not exist in STR.
Support the program with functions for each of the above operations. Don't use Built-in functions.

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

char str[50], pat[50], rep[50];


int start = 0, patfound = 0;
int lasts, lastp, lastr;

void replacepattern()
{
int i, j;
lastr = strlen(rep)-2;

if(lastp != lastr)
{
printf("\nInvalid length of replace string");
exit(0);
}
else
{
i = start;
for(j=0; j<=lastr; j++)
{
str[i] = rep[j];
i++;
}
}
return;
}
void findpattern()
{
int i, j, inmatch;
lasts = (strlen(str))-2;
lastp = (strlen(pat))-2;
int endmatch;

for(endmatch = lastp; endmatch<=lasts; endmatch++, start++)


{
if(str[endmatch] == pat[lastp])
{
inmatch = start;
j=0;
while(j<lastp)
{
if(str[inmatch] == pat[j])
{
inmatch++;
j++;
}
else
{
6
break;
}
}
if(j == lastp)
{
patfound = 1;
replacepattern();
}
}
}
return;
}
void main()
{
printf("\nEnter the main string(STR): ");
fgets(str, 50, stdin);

printf("\nEnter the pattern to be matched(PAT): ");


fgets(pat, 50, stdin);

printf("\nEnter the string to be replaced(REP): ");


fgets(rep, 50, stdin);

printf("\nThe string before pattern match is:\n %s", str);

findpattern();

if(patfound == 0)
printf("\nThe pattern is not found in the main string");
else
printf("\nThe string after pattern match and replace is: \n %s ",str);
return;
}

Output:
Case 1:
Enter the main string(STR): Hello hii how are you hii
Enter the pattern to be matched(PAT): hii
Enter the string to be replaced(REP): xyz
The string before pattern match is:
Hello hii how are you hii
The string after pattern match and replace is:
Hello xyz how are you xyz

Case 2:
Enter the main string(STR): Hello hii how are you
Enter the pattern to be matched(PAT): abc
Enter the string to be replaced(REP): xyz

The string before pattern match is:


Hello hii how are you

The pattern is not found in the main string

7
3. Develop a menu driven Program in C for the following operations on STACK of Integers (Array
Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit

Theory:
A stack is a container of objects that are inserted and removed according to the last-in first-out(LIFO) principle. A stack is a
limited access data structure - elements can be added and removed from the stack only at the top. Push adds an item to the top
of the stack, pop removes the item from the top.

Basic Operations on Stack


In order to make manipulations in a stack, there are certain operations provided to us.
push() to insert an element into the stack
pop() to remove an element from the stack
top() Returns the top element of the stack.
isEmpty() returns true if stack is empty else false.
isFull() returns true if stack is full else false.

Program

#include<stdio.h>
#include<stdlib.h>
#define MAX 5

int s[MAX];
int top = -1;

void push(int item);


int pop();
void palindrome();
void display();

void main()
{
int choice, item;
while(1)
{
printf("\n\n\n\n~~~~~~Menu~~~~~~ : ");
printf("\n=>1.Push an Element to Stack and Overflow demo ");
printf("\n=>2.Pop an Element from Stack and Underflow demo");
printf("\n=>3.Palindrome demo ");
printf("\n=>4.Display ");
printf("\n=>5.Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("\nEnter an element to be pushed: ");
scanf("%d", &item);
push(item);
break;

8
case 2: item = pop();
if(item != -1)
printf("\nElement popped is: %d", item);
break;
case 3: palindrome();
break;
case 4: display();
break;
case 5: exit(1);
default: printf("\nPlease enter valid choice ") ;
break;
}
}
}

void push(int item)


{
if(top == MAX-1)
{
printf("\n~~~~Stack overflow~~~~");
return;
}

top = top + 1 ;
s[top] = item;
}

int pop()
{
int item;
if(top == -1)
{
printf("\n~~~~Stack underflow~~~~");
return -1;
}
item = s[top];
top = top - 1;
return item;
}

void display()
{
int i;
if(top == -1)
{
printf("\n~~~~Stack is empty~~~~");
return;
}
printf("\nStack elements are:\n ");
for(i=top; i>=0 ; i--)
printf("| %d |\n", s[i]);
}

void palindrome()
{
int flag=1,i;
printf("\nStack content are:\n");
for(i=top; i>=0 ; i--)
printf("| %d |\n", s[i]);
9
printf("\nReverse of stack content are:\n");
for(i=0; i<=top; i++)
printf("| %d |\n", s[i]);

for(i=0; i<=top/2; i++)


{
if( s[i] != s[top-i] )
{
flag = 0;
break;
}
}
if(flag == 1)
{
printf("\nIt is palindrome number");
}
else
{
printf("\nIt is not a palindrome number");
}
}

Output:
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 11

~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 12

~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 13

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
10
Enter your choice: 1
Enter an element to be pushed: 16
~~~~Stack overflow~~~~

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4

Stack elements are:


| 15 |
| 14 |
| 13 |
| 12 |
| 11 |

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 15

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 14 |
| 13 |
| 12 |
| 11 |

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 12

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
~~~~Stack underflow~~~~

11
~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
~~~~Stack is empty~~~~

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 11

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 22

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 11

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 3
Stack content are:
| 11 |
| 22 |
| 11 |

Reverse of stack content are:


| 11 |
| 22 |
| 11 |

It is palindrome number

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
12
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 11

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 11

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 22

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 33

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 3
Stack content are:
| 33 |
| 22 |
| 11 |

Reverse of stack content are:


| 11 |
| 22 |
| 33 |

It is not a palindrome number

~~~~~~Menu~~~~~
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 5

13
4. Develop a Program in C for converting an Infix Expression to Postfix Expression. Program should
support for both parenthesized and free parenthesized
a. expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric
operands.

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

void evaluate();
void push(char);
char pop();
int prec(char);

char infix[30], postfix[30], stack[30];


int top = -1;

void main()
{
printf("\nEnter the valid infix expression:\t");
scanf("%s", infix);
evaluate();
printf("\nThe entered infix expression is :\n %s \n", infix);
printf("\nThe corresponding postfix expression is :\n %s \n", postfix);
}

void evaluate()
{
int i = 0, j = 0;
char symb, temp;

push('#');

for(i=0; infix[i] != '\0'; i++)


{
symb = infix[i];
switch(symb)
{
case '(' : push(symb);
break;

case ')' : temp = pop();


while(temp != '(' )
{
postfix[j] = temp;
j++;
temp = pop();
}
break;
case '+' :
case '-' :
case '*' :
case '/' :
case '%' :
case '^' :
14
case '$' : while( prec(stack[top]) >= prec(symb) )
{
temp = pop();
postfix[j] = temp;
j++;
}
push(symb);
break;
default: postfix[j] = symb;
j++;
}
}
while(top > 0)
{
temp = pop();
postfix[j] = temp;
j++;
}
postfix[j] = '\0';
}

void push(char item)


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

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

int prec(char symb)


{
int p;
switch(symb)
{
case '#' : p = -1;
break;

case '(' :
case ')' : p = 0;
break;

case '+' :
case '-' : p = 1;
break;

case '*' :
case '/' :
case '%' : p = 2;
break;

case '^' :
15
case '$' : p = 3;
break;
}
return p;
}

Output:

Enter the valid infix expression: (a+b)+c/d*e

The entered infix expression is :


(a+b)+c/d*e

The corresponding postfix expression is :


ab+cd/e*+

16
5. Develop a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disks

Theory:
a) Evaluation of postfix expression with single digit operands and operators.
For each input symbol,
 If it is a digit then, push it on to the stack.
 If it is an operator then, pop out the top most two contents from the stack and apply the operator on
them. Later on, push the result on to stack.
 If the input symbol is „\0‟, empty the stack.

b) Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings. These rings
are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over the larger one. There are
other variations of the puzzle where the number of disks increase, but the tower count remains the same.
A few rules to be followed for Tower of Hanoi are −
 Only one disk can be moved among the towers at any given time.
 Only the "top" disk can be removed.
 No large disk can sit over a small disk.

Program (a):
#include<stdio.h>
#include<math.h>
#include<ctype.h>
char s[50],ch;
int i,a,b,top=-1,stk[50],ans,num,elm;
void push(int num)
{
top=top+1;
stk[top]=num;
}
int pop()
{
elm=stk[top];
top=top-1;
return (elm);
}
void main()
{
printf("Enter the postfix expression\n");
scanf("%s",s);
for(i=0;s[i]!='\0';i++)
{
ch=s[i];
if(isdigit(ch))
push(ch-'0');
else
{
b=pop();
a=pop();
switch(ch)
{
case '+':push(a+b);
17
break;
case '-':push(a-b);
break;
case '*':push(a*b);
break;
case '/':push(a/b);
break;
case '%':push(a%b);
break;
case '$':push(pow(a,b));
break;
case '^':push(pow(a,b));
break;
default:printf("Invalid operator\n");
}
}
}
ans=pop();
printf("Result of given expression= %d\n",ans);
}

Output:
Enter the postfix expression
53+62/*35*+
Result of given expression= 39

18
Program (b):
#include<stdio.h>
#include<math.h>
int n,x;
void tower(int n,char a,char b,char c)
{
if(n==1)
{
printf("Move disk from %c to %c\n",a,c);
}
tower(n-1,a,c,b);
printf("Move disk from %c to %c\n",a,c);
tower(n-1,b,a,c);
}
void main()
{
printf("Enter number of disks\n");
scanf("%d",&n);
tower(n,'A','B','C');
x=pow(2,n)-1;
printf("Number of moves = %d\n",x);
}

Output:
Enter the number of disks
3
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C
Number of moves= 7

19
6.Develop a menu driven Program in C for the following operations on Circular QUEUE of Characters
(Array Implementation of Queue with maximum size MAX)
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit
Support the program with appropriate functions for each of the above operations

#include <stdio.h>
#define MAX 5
char cq[MAX];
int front = -1, rear = -1;

void main()
{
int ch;
char item;
while(1)
{
printf("\n\nMain Menu");
printf("\n1. Insertion and Overflow ");
printf("\n 2. Deletion and Underflow ");
printf("\n 3. Display");
printf("\n 4. Exit");
printf("\nEnter Your Choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\n\nEnter the element to be inserted: ");
scanf("%c", &item);
insert(item);
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\n\nPlease enter a valid choice");
}
}
}
void insert(char item)
{
if(front == (rear+1)%MAX)
{
printf("\n\nCircular Queue Overflow");
}
else
{
if(front == -1)
front = rear = 0;
else
rear = (rear+1)%MAX;
cq[rear] = item;
20
}
}
void delete()
{
char item;
if(front == -1)
{
printf("\n\nCircular Queue Underflow");
}
else
{
item = cq[front];
printf("\n\nDeleted element from the queue is: %c ",item );

if(front == rear) //only one element


front = rear = -1;
else
front = (front+1)%MAX;
}
}
void display ()
{
int i ;
if(front == -1)
{
printf("\n\nCircular Queue Empty");
}
else
{
printf("\nCircular Queue contents are:\n");

for(i = front; i != rear ; i = (i+1)%MAX)


{
printf(" %c", cq[i]);
}
printf(" %c", cq[i]);

}
}

Output:
Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 1

Enter the element to be inserted: A

Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 1
Enter the element to be inserted: B
21
Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 1
Enter the element to be inserted: C

Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 1

Enter the element to be inserted: D


Circular Queue Overflow

Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 3

Circular Queue contents are:


ABC

Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 2

Deleted element from the queue is: A

Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 3
Circular Queue contents are:
BC

Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 1

Enter the element to be inserted: E

Main Menu
22
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 3

Circular Queue contents are:


BCE

Main Menu
1. Insertion and Overflow
2. Deletion and Underflow
3. Display
4. Exit
Enter Your Choice: 4

23
7.Develop a menu driven Program in C for the following operations on Singly Linked List (SLL) of
Student Data with the fields: USN, Name, Programme, Sem,PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit.

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

struct node
{
char usn[25],name[25],branch[25];
int sem;
long int phone;
struct node *link;
};
typedef struct node * NODE;

NODE start = NULL;


int count=0;

NODE create()
{
NODE snode;
snode = (NODE)malloc(sizeof(struct node));

if(snode == NULL)
{
printf("\nMemory is not available");
exit(1);
}
printf("\nEnter the usn,Name,Branch, sem,PhoneNo of the student:");
scanf("%s %s %s %d %ld",snode->usn, snode->name, snode->branch, &snode->sem, &snode->phone);
snode->link=NULL;
count++;
return snode;
}

NODE insertfront()
{
NODE temp;
temp = create();
if(start == NULL)
{
return temp;
}

temp->link = start;
return temp;
}

24
NODE deletefront()
{
NODE temp;
if(start == NULL)
{
printf("\nLinked list is empty");
return NULL;
}
if(start->link == NULL)
{
printf("\nThe Student node with usn:%s is deleted ",start->usn);
count--;
free(start);
return NULL;
}
temp = start;
start = start->link;
printf("\nThe Student node with usn:%s is deleted",temp->usn);
count--;
free(temp);
return start;
}

NODE insertend()
{
NODE cur,temp;
temp = create();

if(start == NULL)
{
return temp;
}
cur = start;
while(cur->link !=NULL)
{
cur = cur->link;
}
cur->link = temp;
return start;
}

NODE deleteend()
{
NODE cur,prev;
if(start == NULL)
{
printf("\nLinked List is empty");
return NULL;
}

if(start->link == NULL)
{
printf("\nThe student node with the usn:%s is deleted",start->usn);
free(start);
count--;
return NULL;
25
}

prev = NULL;
cur = start;
while(cur->link!=NULL)
{
prev = cur;
cur = cur->link;
}

printf("\nThe student node with the usn:%s is deleted",cur->usn);


free(cur);
prev->link = NULL;
count--;
return start;
}

void display()
{
NODE cur;
int num=1;

if(start == NULL)
{

printf("\nNo Contents to display in SLL \n");


return;
}
printf("\nThe contents of SLL: \n");
cur = start;
while(cur!=NULL)
{
printf("\n||%d|| USN:%s| Name:%s| Branch:%s| Sem:%d| Ph:%ld|",num,cur->usn, cur->name,cur->branch, cur-
>sem,cur->phone);
cur = cur->link;
num++;
}
printf("\n No of student nodes is %d \n",count);
}

void stackdemo()
{
int ch;
while(1)
{
printf("\nStack Demo using SLL\n");
printf("\n1:Push operation \n2: Pop operation \n3: Display \n4:Exit \n");
printf("\nEnter your choice for stack demo");
scanf("%d",&ch);

switch(ch)
{
case 1: start = insertfront();
break;
case 2: start = deletefront();
break;
26
case 3: display();
break;
default : return;
}
}
return;
}

int main()
{
int ch,i,n;
while(1)
{
printf("\nMenu");
printf("\nEnter your choice for SLL operation \n");
printf("\n1:Create SLL of Student Nodes");
printf("\n2:DisplayStatus");
printf("\n3:InsertAtEnd");
printf("\n4:DeleteAtEnd");
printf("\n5:Stack Demo using SLL(Insertion and Deletion at Front)");
printf("\n6:Exit \n");
printf("\nEnter your choice:");
scanf("%d",&ch);

switch(ch)
{
case 1 : printf("\nEnter the no of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
start = insertfront();
break;

case 2: display();
break;

case 3: start = insertend();


break;

case 4: start = deleteend();


break;

case 5: stackdemo();
break;

case 6: exit(0);

default: printf("\nPlease enter the valid choice");

}
}
}

27
Output:

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:1

Enter the no of students: 3

Enter the usn,Name,Branch, sem,PhoneNo of the student:


111
aaa
cs
1
111111

Enter the usn,Name,Branch, sem,PhoneNo of the student:


222
bbb
ec
2
222222

Enter the usn,Name,Branch, sem,PhoneNo of the student:


333
ccc
ec
3
333333

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:2

The contents of SLL:

||1|| USN:333| Name:ccc| Branch:ec| Sem:3| Ph:333333|


||2|| USN:222| Name:bbb| Branch:ec| Sem:2| Ph:222222|
||3|| USN:111| Name:aaa| Branch:cs| Sem:1| Ph:111111|
No of student nodes is 3

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
28
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:3

Enter the usn,Name,Branch, sem,PhoneNo of the student:


444
ddd
ec
4
444444

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:2

The contents of SLL:

||1|| USN:333| Name:ccc| Branch:ec| Sem:3| Ph:333333|


||2|| USN:222| Name:bbb| Branch:ec| Sem:2| Ph:222222|
||3|| USN:111| Name:aaa| Branch:cs| Sem:1| Ph:111111|
||4|| USN:444| Name:ddd| Branch:ec| Sem:4| Ph:444444|
No of student nodes is 4

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:4

The student node with the usn: 444 is deleted

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:2

The contents of SLL:


29
||1|| USN:333| Name:ccc| Branch:ec| Sem:3| Ph:333333|
||2|| USN:222| Name:bbb| Branch:ec| Sem:2| Ph:222222|
||3|| USN:111| Name:aaa| Branch:cs| Sem:1| Ph:111111|
No of student nodes is 3

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:4

The student node with the usn: 111 is deleted

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit Enter your choice:5

Stack Demo using SLL


1:Push operation
2: Pop operation
3: Display
4:Exit
Enter your choice for stack demo: 1

Enter the usn,Name,Branch, sem,PhoneNo of the student:


555
eee
cs
1
555555

Stack Demo using SLL


1:Push operation
2: Pop operation
3: Display
4:Exit
Enter your choice for stack demo:3

The contents of SLL:

||1|| USN:555| Name:eee| Branch:cs| Sem:1| Ph:555555|


||2|| USN:333| Name:ccc| Branch:ec| Sem:3| Ph:333333|
||3|| USN:222| Name:bbb| Branch:ec| Sem:2| Ph:222222|
No of student nodes is 3
30
Stack Demo using SLL
1:Push operation
2: Pop operation
3: Display
4:Exit
Enter your choice for stack demo: 1

Enter the usn,Name,Branch, sem,PhoneNo of the student:


666
fff
cs
6
666666

Stack Demo using SLL


1:Push operation
2: Pop operation
3: Display
4:Exit
Enter your choice for stack demo: 3

The contents of SLL:

||1|| USN:666| Name:fff| Branch:cs| Sem:6| Ph:666666|


||2|| USN:555| Name:eee| Branch:cs| Sem:1| Ph:555555|
||3|| USN:333| Name:ccc| Branch:ec| Sem:3| Ph:333333|
||4|| USN:222| Name:bbb| Branch:ec| Sem:2| Ph:222222|
No of student nodes is 4

Stack Demo using SLL


1:Push operation
2: Pop operation
3: Display
4:Exit
Enter your choice for stack demo: 2

The Student node with usn: 666 is deleted

Stack Demo using SLL


1:Push operation
2: Pop operation
3: Display
4:Exit
Enter your choice for stack demo: 3

The contents of SLL:

||1|| USN:555| Name:eee| Branch:cs| Sem:1| Ph:555555|


||2|| USN:333| Name:ccc| Branch:ec| Sem:3| Ph:333333|
||3|| USN:222| Name:bbb| Branch:ec| Sem:2| Ph:222222|
No of student nodes is 3

Stack Demo using SLL


1:Push operation
2: Pop operation
31
3: Display
4:Exit
Enter your choice for stack demo: 4

Menu
Enter your choice for SLL operation
1:Create SLL of Student Nodes
2:Display Status
3:Insert At End
4:Delete At End
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:Exit
Enter your choice:6

32
8. Develop a menu driven Program in C for the following operations on Doubly Linked List (DLL) of
Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue.
f. Exit

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

struct node
{
char ssn[25],name[25],dept[10],designation[25];
int sal;
long int phone;
struct node *llink;
struct node *rlink;
};
typedef struct node* NODE;

NODE first = NULL;


int count=0;

NODE create()
{
NODE enode;
enode = (NODE)malloc(sizeof(struct node));
if( enode== NULL)
{
printf("\nRunning out of memory");
exit(0);
}
printf("\nEnter the ssn,Name,Department,Designation,Salary,PhoneNo of the employee: \n");
scanf("%s %s %s %s %d %ld", enode->ssn, enode->name, enode->dept, enode->designation, &enode->sal, &enode-
>phone);
enode->llink=NULL;
enode->rlink=NULL;
count++;
return enode;
}

NODE insertfront()
{
NODE temp;
temp = create();
if(first == NULL)
{
return temp;
}
temp->rlink = first;
first->llink = temp;
return temp;
}
33
void display()
{
NODE cur;
int nodeno=1;
cur = first;
if(cur == NULL)
printf("\nNo Contents to display in DLL");
while(cur!=NULL)
{
printf("\nENode:%d||SSN:%s|Name:%s|Department:%s|Designation:%s|Salary:%d|Phone no:%ld", nodeno, cur->ssn, cur-
>name,cur->dept, cur->designation, cur->sal, cur->phone);
cur = cur->rlink;
nodeno++;
}
printf("\nNo of employee nodes is %d",count);
}

NODE deletefront()
{
NODE temp;
if(first == NULL)
{
printf("\nDoubly Linked List is empty");
return NULL;
}
if(first->rlink== NULL)
{
printf("\nThe employee node with the ssn:%s is deleted", first->ssn);
free(first);
count--;
return NULL;
}
temp = first;
first = first->rlink;
temp->rlink = NULL;
first->llink = NULL;
printf("\nThe employee node with the ssn:%s is deleted",temp->ssn);
free(temp);
count--;
return first;
}

NODE insertend()
{
NODE cur, temp;
temp = create();

if(first == NULL)
{
return temp;
}
cur= first;
while(cur->rlink!=NULL)
{
cur = cur->rlink;
}
34
cur->rlink = temp;
temp->llink = cur;
return first;
}

NODE deleteend()
{
NODE prev,cur;
if(first == NULL)
{
printf("\nDoubly Linked List is empty");
return NULL;
}

if(first->rlink == NULL)
{
printf("\nThe employee node with the ssn:%s is deleted",first->ssn);
free(first);
count--;
return NULL;
}

prev=NULL;
cur=first;

while(cur->rlink!=NULL)
{
prev=cur;
cur = cur->rlink;
}

cur->llink = NULL;
printf("\nThe employee node with the ssn:%s is deleted",cur->ssn);
free(cur);
prev->rlink = NULL;
count--;
return first;
}

void deqdemo()
{
int ch;
while(1)
{
printf("\nDemo Double Ended Queue Operation");
printf("\n1:InsertQueueFront\n 2: DeleteQueueFront\n 3:InsertQueueRear\n 4:DeleteQueueRear\n 5:DisplayStatus\n 6: Exit
\n");
scanf("%d", &ch);

switch(ch)
{
case 1: first=insertfront();
break;
case 2: first=deletefront();
break;
case 3: first=insertend();
35
break;
case 4: first=deleteend();
break;
case 5: display();
break;
default : return;
}
}
}

void main()
{
int ch,i,n;
while(1)
{
printf("\n\n~~~Menu~~~");
printf("\n1:Create DLL of Employee Nodes");
printf("\n2:DisplayStatus");
printf("\n3:InsertAtEnd");
printf("\n4:DeleteAtEnd");
printf("\n5:InsertAtFront");
printf("\n6:DeleteAtFront");
printf("\n7:Double Ended Queue Demo using DLL");
printf("\n8:Exit \n");
printf("\nPlease enter your choice: ");
scanf("%d",&ch);

switch(ch)
{
case 1 : printf("\nEnter the no of Employees: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
first = insertend();
break;

case 2: display();
break;

case 3: first = insertend();


break;

case 4: first = deleteend();


break;

case 5: first = insertfront();


break;

case 6: first = deletefront();


break;

case 7: deqdemo();
break;

case 8 : exit(0);
default: printf("\nPlease Enter the valid choice");
}

36
}
}

Output:
~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 1
Enter the no of Employees: 2

Enter the ssn,Name,Department,Designation,Salary,PhoneNo of the employee:


111
aaa
dept1
des1
1000
11111

Enter the ssn,Name,Department,Designation,Salary,PhoneNo of the employee:


222
bbb
dept2
des2
2000
22222

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 2

ENode:1||SSN:111|Name:aaa|Department:dept1|Designation:des1|Salary:1000|Phone no:11111
ENode:2||SSN:222|Name:bbb|Department:dept2|Designation:des2|Salary:2000|Phone no:22222
No of employee nodes is 2

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 3
37
Enter the ssn,Name,Department,Designation,Salary,PhoneNo of the employee:
333
ccc
dept3
des3
3000
33333

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 2

ENode:1||SSN:111|Name:aaa|Department:dept1|Designation:des1|Salary:1000|Phone no:11111
ENode:2||SSN:222|Name:bbb|Department:dept2|Designation:des2|Salary:2000|Phone no:22222
ENode:3||SSN:333|Name:ccc|Department:dept3|Designation:des3|Salary:3000|Phone no:33333
No of employee nodes is 3

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 5

Enter the ssn,Name,Department,Designation,Salary,PhoneNo of the employee:


444
ddd
dept4
des4
4000
44444

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit

Please enter your choice: 2

ENode:1||SSN:444|Name:ddd|Department:dept4|Designation:des4|Salary:4000|Phone no:44444
38
ENode:2||SSN:111|Name:aaa|Department:dept1|Designation:des1|Salary:1000|Phone no:11111
ENode:3||SSN:222|Name:bbb|Department:dept2|Designation:des2|Salary:2000|Phone no:22222
ENode:4||SSN:333|Name:ccc|Department:dept3|Designation:des3|Salary:3000|Phone no:33333
No of employee nodes is 4

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 4

The employee node with the ssn:333 is deleted

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 6

The employee node with the ssn:444 is deleted

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 2

ENode:1||SSN:111|Name:aaa|Department:dept1|Designation:des1|Salary:1000|Phone no:11111
ENode:2||SSN:222|Name:bbb|Department:dept2|Designation:des2|Salary:2000|Phone no:22222
No of employee nodes is 2

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit
Please enter your choice: 7

39
Demo Double Ended Queue Operation
1:InsertQueueFront
2: DeleteQueueFront
3:InsertQueueRear
4:DeleteQueueRear
5:DisplayStatus
6: Exit
2

The employee node with the ssn:111 is deleted

Demo Double Ended Queue Operation


1:InsertQueueFront
2: DeleteQueueFront
3:InsertQueueRear
4:DeleteQueueRear
5:DisplayStatus
6: Exit
4

The employee node with the ssn:222 is deleted

Demo Double Ended Queue Operation


1:InsertQueueFront
2: DeleteQueueFront
3:InsertQueueRear
4:DeleteQueueRear
5:DisplayStatus
6: Exit
2

Doubly Linked List is empty

Demo Double Ended Queue Operation


1:InsertQueueFront
2: DeleteQueueFront
3:InsertQueueRear
4:DeleteQueueRear
5:DisplayStatus
6: Exit
6

~~~Menu~~~
1:Create DLL of Employee Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:InsertAtFront
6:DeleteAtFront
7:Double Ended Queue Demo using DLL
8:Exit

Please enter your choice: 8

40
9. Develop a Program in C for the following operationson Singly Circular Linked List (SCLL) with header
nodes
a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result in
POLYSUM(x,y,z).
Support the program with appropriate functions for each of the above operations

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define COMPARE(x, y) ( (x == y) ? 0 : (x > y) ? 1 : -1)

struct node
{
int coef;
int xexp, yexp, zexp;
struct node *link;
};
typedef struct node *NODE;

NODE getnode()
{
NODE x;
x = (NODE) malloc(sizeof(struct node));
if(x == NULL)
{
printf("Running out of memory \n");
return NULL;
}
return x;
}

NODE attach(int coef, int xexp, int yexp, int zexp, NODE head)
{
NODE temp, cur;
temp = getnode();
temp->coef = coef;
temp->xexp = xexp;
temp->yexp = yexp;
temp->zexp = zexp;
cur = head->link;
while(cur->link != head)
{
cur = cur->link;
}
cur->link = temp;
temp->link = head;
return head;
}

NODE read_poly(NODE head)


{
int i, j, coef, xexp, yexp, zexp, n;
printf("\nEnter the no of terms in the polynomial: ");
scanf("%d", &n);
41
for(i=1; i<=n; i++)
{
printf("\n\tEnter the %d term: ",i);
printf("\n\t\tCoef = ");
scanf("%d", &coef);
printf("\n\t\tEnter Pow(x) Pow(y) and Pow(z): ");
scanf("%d", &xexp);
scanf("%d", &yexp);
scanf("%d", &zexp);
head = attach(coef, xexp, yexp, zexp, head);
}
return head;
}

void display(NODE head)


{
NODE temp;
if(head->link == head)
{
printf("\nPolynomial does not exist.");
return;
}
temp = head->link;

while(temp != head)
{
printf("%dx^%dy^%dz^%d", temp->coef, temp->xexp, temp->yexp, temp->zexp);
temp = temp->link;
if(temp != head)
printf(" + ");
}
}

int poly_evaluate(NODE head)


{
int x, y, z, sum = 0;
NODE poly;

printf("\nEnter the value of x,y and z: ");


scanf("%d %d %d", &x, &y, &z);

poly = head->link;
while(poly != head)
{
sum += poly->coef * pow(x,poly->xexp)* pow(y,poly->yexp) * pow(z,poly->zexp);
poly = poly->link;
}
return sum;
}

NODE poly_sum(NODE head1, NODE head2, NODE head3)


{
NODE a, b;
int coef;
a = head1->link;
b = head2->link;

42
while(a!=head1 && b!=head2)
{
while(1)
{
if(a->xexp == b->xexp && a->yexp == b->yexp && a->zexp == b->zexp)
{
coef = a->coef + b->coef;
head3 = attach(coef, a->xexp, a->yexp, a->zexp, head3);
a = a->link;
b = b->link;
break;
} //if ends here
if(a->xexp!=0 || b->xexp!=0)
{
switch(COMPARE(a->xexp, b->xexp))
{
case -1 : head3 = attach(b->coef, b->xexp, b->yexp, b->zexp, head3);
b = b->link;
break;

case 0 : if(a->yexp > b->yexp)


{
head3 = attach(a->coef, a->xexp, a->yexp, a->zexp, head3);
a = a->link;
break;
}
else if(a->yexp < b->yexp)
{
head3 = attach(b->coef, b->xexp, b->yexp, b->zexp, head3);
b = b->link;
break;
}
else if(a->zexp > b->zexp)
{
head3 = attach(a->coef, a->xexp, a->yexp, a->zexp, head3);
a = a->link;
break;
}
else if(a->zexp < b->zexp)
{
head3 = attach(b->coef, b->xexp, b->yexp, b->zexp, head3);
b = b->link;
break;
}
case 1 : head3 = attach(a->coef,a->xexp,a->yexp,a->zexp,head3);
a = a->link;
break;
} //switch ends here
break;
} //if ends here
if(a->yexp!=0 || b->yexp!=0)
{
switch(COMPARE(a->yexp, b->yexp))
{
case -1 : head3 = attach(b->coef, b->xexp, b->yexp, b->zexp, head3);

43
b = b->link;
break;
case 0 : if(a->zexp > b->zexp)
{
head3 = attach(a->coef, a->xexp, a->yexp, a->zexp, head3);
a = a->link;
break;
}
else if(a->zexp < b->zexp)
{
head3 = attach(b->coef, b->xexp, b->yexp, b->zexp, head3);
b = b->link;
break;
}
case 1 : head3 = attach(a->coef, a->xexp, a->yexp, a->zexp, head3);
a = a->link;
break;
}
break;
}
if(a->zexp!=0 || b->zexp!=0)
{
switch(COMPARE(a->zexp,b->zexp))
{
case -1 : head3 = attach(b->coef,b->xexp,b->yexp,b->zexp,head3);
b = b->link;
break;
case 1 : head3 = attach(a->coef, a->xexp, a->yexp, a->zexp, head3);
a = a->link;
break;
}
break;
}
}
}
while(a!= head1)
{
head3 = attach(a->coef,a->xexp,a->yexp,a->zexp,head3);
a = a->link;
}
while(b!= head2)
{
head3 = attach(b->coef,b->xexp,b->yexp,b->zexp,head3);
b = b->link;
}
return head3;
}

void main()
{
NODE head, head1, head2, head3;
int res, ch;
head = getnode(); /* For polynomial evalaution */
head1 = getnode(); /* To hold POLY1 */
head2 = getnode(); /* To hold POLY2 */
head3 = getnode(); /* To hold POLYSUM */

44
head->link=head;
head1->link=head1;
head2->link=head2;
head3->link= head3;

while(1)
{
printf("\n~~~Menu~~~");
printf("\n1.Represent and Evaluate a Polynomial P(x,y,z)");
printf("\n2.Find the sum of two polynomials POLY1(x,y,z)");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n~~~~Polynomial evaluation P(x,y,z)~~~\n");
head = read_poly(head);
printf("\nRepresentation of Polynomial for evaluation: \n");
display(head);
res = poly_evaluate(head);
printf("\nResult of polynomial evaluation is : %d \n", res);
break;

case 2: printf("\nEnter the POLY1(x,y,z): \n");


head1 = read_poly(head1);
printf("\nPolynomial 1 is: \n");
display(head1);

printf("\nEnter the POLY2(x,y,z): \n");


head2 = read_poly(head2);
printf("\nPolynomial 2 is: \n");
display(head2);

printf("\nPolynomial addition result: \n");


head3 = poly_sum(head1,head2,head3);
display(head3);
break;
case 3: exit(0);
}
}
}

Output:
~~~Menu~~~
1.Represent and Evaluate a Polynomial P(x,y,z)
2.Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z)
Enter your choice: 1

~~~~Polynomial evaluation P(x,y,z)~~~


Enter the no of terms in the polynomial: 5
Enter the 1 term:
Coef = 6
Enter Pow(x) Pow(y) and Pow(z): 2 2 1
Enter the 2 term:

45
Coef = -4
Enter Pow(x) Pow(y) and Pow(z): 0 1 5
Enter the 3 term:
Coef = 3
Enter Pow(x) Pow(y) and Pow(z): 3 1 1
Enter the 4 term:
Coef = 2
Enter Pow(x) Pow(y) and Pow(z): 1 5 1
Enter the 5 term:
Coef = -2
Enter Pow(x) Pow(y) and Pow(z): 1 1 3
Representation of Polynomial for evaluation:
6x^2y^2z^1 + -4x^0y^1z^5 + 3x^3y^1z^1 + 2x^1y^5z^1 + -2x^1y^1z^3
Enter the value of x,y and z: 1 1 1
Result of polynomial evaluation is : 5

~~~Menu~~~
1.Represent and Evaluate a Polynomial P(x,y,z)
2.Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z)
Enter your choice: 2

Enter the POLY1(x,y,z):


Enter the no of terms in the polynomial: 5
Enter the 1 term:
Coef = 6
Enter Pow(x) Pow(y) and Pow(z): 4 4 4
Enter the 2 term:
Coef = 3
Enter Pow(x) Pow(y) and Pow(z): 4 3 1
Enter the 3 term:
Coef = 5
Enter Pow(x) Pow(y) and Pow(z): 0 1 1
Enter the 4 term:
Coef = 10
Enter Pow(x) Pow(y) and Pow(z): 0 1 0
Enter the 5 term:
Coef = 5
Enter Pow(x) Pow(y) and Pow(z): 0 0 0
Polynomial 1 is:
6x^4y^4z^4 + 3x^4y^3z^1 + 5x^0y^1z^1 + 10x^0y^1z^0 + 5x^0y^0z^0

Enter the POLY2(x,y,z):


Enter the no of terms in the polynomial: 5
Enter the 1 term:
Coef = 8
Enter Pow(x) Pow(y) and Pow(z): 4 4 4
Enter the 2 term:
Coef = 4
Enter Pow(x) Pow(y) and Pow(z): 4 2 1
Enter the 3 term:
Coef = 30
Enter Pow(x) Pow(y) and Pow(z): 0 1 0
Enter the 4 term:
Coef = 20

46
Enter Pow(x) Pow(y) and Pow(z): 0 0 1
Enter the 5 term:
Coef = 3
Enter Pow(x) Pow(y) and Pow(z): 0 0 0
Polynomial 2 is:
8x^4y^4z^4 + 4x^4y^2z^1 + 30x^0y^1z^0 + 20x^0y^0z^1 + 3x^0y^0z^0

Polynomial addition result:


14x^4y^4z^4 + 3x^4y^3z^1 + 4x^4y^2z^1 + 5x^0y^1z^1 + 40x^0y^1z^0 + 20x^0y^0z^1 + 8x^0y^0z^0

~~~Menu~~~
1.Represent and Evaluate a Polynomial P(x,y,z)
2.Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z)
Enter your choice:3

47
10.Develop a menu driven Program in C for the following operations on Binary Search Tree (BST) of
Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit

#include<stdio.h>
#include<stdlib.h>
struct BST
{
int data;
struct BST *lchild;
struct BST *rchild;
};
typedef struct BST * NODE;

NODE create()
{
NODE temp;
temp = (NODE) malloc(sizeof(struct BST));
printf("\nEnter The value: ");
scanf("%d", &temp->data);

temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}

void insert(NODE root, NODE newnode);


void inorder(NODE root);
void preorder(NODE root);
void postorder(NODE root);
void search(NODE root);

void insert(NODE root, NODE newnode)


{
/*Note: if newnode->data == root->data it will be skipped. No duplicate nodes are allowed */

if (newnode->data < root->data)


{
if (root->lchild == NULL)
root->lchild = newnode;
else
insert(root->lchild, newnode);
}
if (newnode->data > root->data)
{
if (root->rchild == NULL)
root->rchild = newnode;
else
insert(root->rchild, newnode);
}

48
}

void search(NODE root)


{
int key;
NODE cur;
if(root == NULL)
{
printf("\nBST is empty.");
return;
}
printf("\nEnter Element to be searched: ");
scanf("%d", &key);
cur = root;
while (cur != NULL)
{
if (cur->data == key)
{
printf("\nKey element is present in BST");
return;
}
if (key < cur->data)
cur = cur->lchild;
else
cur = cur->rchild;
}
printf("\nKey element is not found in the BST");
}

void inorder(NODE root)


{
if(root != NULL)
{
inorder(root->lchild);
printf("%d ", root->data);
inorder(root->rchild);
}
}

void preorder(NODE root)


{
if (root != NULL)
{
printf("%d ", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}

void postorder(NODE root)


{
if (root != NULL)
{
postorder(root->lchild);
postorder(root->rchild);

49
printf("%d ", root->data);
}
}

void main()
{
int ch, key, val, i, n;
NODE root = NULL, newnode;
while(1)
{
printf("\n~~~~BST MENU~~~~");
printf("\n1.Create a BST");
printf("\n2.Search");
printf("\n3.BST Traversals: ");
printf("\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\nEnter the number of elements: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
newnode = create();
if (root == NULL)
root = newnode;
else
insert(root, newnode);
}
break;
case 2: if (root == NULL)
printf("\nTree Is Not Created");
else
{
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}

break;
case 3: search(root);
break;

case 4: exit(0);
}
}
}

Output:
~~~~BST MENU~~~~
1.Create a BST
2.Search

50
3.BST Traversals:
4.Exit
Enter your choice: 1

Enter the number of elements: 12


Enter The value: 6
Enter The value: 9
Enter The value: 5
Enter The value: 2
Enter The value: 8
Enter The value: 15
Enter The value: 24
Enter The value: 14
Enter The value: 7
Enter The value: 8
Enter The value: 5
Enter The value: 2

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 3

The Preorder display: 6 5 2 9 8 7 15 14 24


The Inorder display: 2 5 6 7 8 9 14 15 24
The Postorder display: 2 5 7 8 14 24 15 9 6

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2

Enter Element to be searched: 66


Key element is not found in the BST

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2

Enter Element to be searched: 14


Key element is present in BST

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 4

51
11.Develop a Program in C for the following operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS method

#include
<stdio.h>#include<stdl
ib.h>
inta[20][20],q[20],visited[20],reach[10],n,i,j,f=0,r=-1,count=0;

void bfs(int v)
{
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
void dfs(int v)
{
int i;reach[v]=1;
for(i=1;i<=n;i++)
{
if(a[v][i] &&!reach[i])
{
printf("\n %d->%d",v,i);
count++;
dfs(i);
}
}
}
voidmain()
{
intv,choice;
printf("\nEnterthenumberofvertices:");scanf("%d"
,&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
for(i=1;i<=n-
1;i++)reach[i]=0;

52
printf("\nEntergraphdatainmatrix
form:\n");for(i=1;i<=n;i++)
for(j=1;j<=n;j++)scanf("%d",&a[i][j]);printf("1.BFS\n 2.DFS\n 3.Exit\n");scanf("%d",&choice);
switch(choice)
{
case1:printf("\nEnterthestartingvertex:");scanf("
%d",&v);
bfs(v);
if((v<1)||(v>n))
{
printf("\n Bfsisnotpossible");
}
else
{
printf("\n The nodes which are reachable from
%d:\n",v);for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
}
break;
case 2:dfs(1);
if(count==n-1)
printf("\n Graph is connected");
else
printf("\nGraphisnotconnected");
break;
case3:exit(0);
}
}

Output
linux:~/dslab#geditbfs.clinux:
~/dslab #gcc
bfs.clinux:~/dslab# ./a.out

Enter the number of vertices:5


Enter graph data in matrix form:
01010
10101
01010
10100
01000
1. BFS
2. DFS
3. Exit
2

1->2
53
2->3
3->4
2->5
Graph is connected
Enterthenumberofvertices:5
Enter graph data in matrix form:
01010
10100
01010
10100
00000
1. BFS
2. DFS
3. Exit
2

1->2
2->3
3->4
Graphisnotconnected
Enterthenumberof vertices:5
Enter graph data in matrix form:
01100
00010
00000
00100
00100
1. BFS
2. DFS
3. Exit
1
Enterthestartingvertex:1
Thenodeswhicharereachablefrom1:2 3 4

Enter graph data in matrix form:


01100
00010
00000
00100
00100
1. BFS
2.DFS3
.Exit1
Enterthestartingvertex:0
BFSis not possible

54
12. Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine the records in
file F. Assume that file F is maintained in memory by a Hash Table (HT) of m memory locations with L as the
set of memory addresses (2-digit) of locations in HT. Let the keys in K and addresses in L are Integers. Develop
a Program in C that uses Hash function H:
K →L as H(K)=K mod m (remainder method), and implement hashing technique to map a given key K to the
address space L. Resolve the collision (if any) using linear probing.

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

int key[20],n,m;
int *ht,index;
int count = 0;

void insert(int key)


{
index = key % m;
while(ht[index] != -1)
{
index = (index+1)%m;
}
ht[index] = key;
count++;
}

void display()
{
int i;
if(count == 0)
{
printf("\nHash Table is empty");
return;
}

printf("\nHash Table contents are:\n ");


for(i=0; i<m; i++)
printf("\n T[%d] --> %d ", i, ht[i]);
}

void main()
{
int i;
printf("\nEnter the number of employee records (N) : ");
scanf("%d", &n);

printf("\nEnter the two digit memory locations (m) for hash table: ");
scanf("%d", &m);

ht = (int *)malloc(m*sizeof(int));
for(i=0; i<m; i++)
ht[i] = -1;

printf("\nEnter the four digit key values (K) for N Employee Records:\n ");
for(i=0; i<n; i++)
scanf("%d", &key[i]);

for(i=0;i<n;i++)
{
if(count == m)
{
printf("\n~~~Hash table is full. Cannot insert the record %d key~~~",i+1);
55
break;
}
insert(key[i]);
}

//Displaying Keys inserted into hash table


display();
}

Output:
Enter the number of employee records (N) : 12

Enter the two digit memory locations (m) for hash table: 15
Enter the four digit key values (K) of 'N' Employee Records:
1234
5678
3456
2345
6799
1235
7890
3214
3456
1235
5679
2346

Hash Table contents are:

T[0] --> 7890


T[1] --> -1
T[2] --> -1
T[3] --> -1
T[4] --> 1234
T[5] --> 2345
T[6] --> 3456
T[7] --> 6799
T[8] --> 5678
T[9] --> 1235
T[10] --> 3214
T[11] --> 3456
T[12] --> 1235
T[13] --> 5679
T[14] --> 2346

56
VIVAQUESTIONSANDANSWERS
1) Whatisdatastructure?
Data structures refer to the way data is organized and manipulated. It seeks to find ways to make data
accessmore efficient. When dealing with data structure, we not only focus on one piece of data, but rather
differentsetof data and how theycan relate tooneanotherin an organized manner.
2) Differentiatefilestructurefromstoragestructure.
Basically, the key difference is the memory area that is being accessed. When dealing with the structure
thatresides the main memory of the computer system, this is referred to as storage structure. When dealing
withanauxiliarystructure, we refer to it as file structures.
3) Whenisabinarysearchbestapplied?
A binary search is an algorithm that is best applied to search a list when the elements are already in order
orsorted. The list is search starting in the middle, such that if that middle value is not the target search key,
itwill check to see if it will continue the search on the lower half of the list or the higher half. The split
andsearchwill then continuein thesamemanner.
4) Whatis alinked list?
A linked list is a sequence of nodes in which each node is connected to the node following it. This forms
achain-likelink ofdata storage.
5) How doyoureferencealltheelementsinaone-dimension array?
To do this, an indexed loop is used, such that the counter runs from 0 to the array size minus one. In
thismanner,weareableto referenceallthe elements insequencebyusingthe loop counterasthearraysubscript.
6) Inwhatareasdodatastructuresapplied?
Data structures is important in almost every aspect where data is involved. In general, algorithms that
involveefficient data structure is applied in the following areas: numerical analysis, operating system, A.I.,
compilerdesign,databasemanagement, graphics, andstatisticalanalysis, to nameafew.
7) WhatisLIFO?
LIFO is short for Last in First Out, and refers to how data is accessed, stored and retrieved. Usingthisscheme,
data that was stored last, should be the one to be extracted first. This also means that in order to gainaccess to
the first data, all the other data that was stored before this first data must first be retrieved andextracted.
8) Whatis a queue?
A queue is a data structure that can simulates a list or stream of data. In this structure, new elements
areinsertedat oneend and existingelements areremoved from the otherend.
9) Whatarebinary trees?
A binary tree is one type of data structure that has two nodes, a left node and a right node. In
programming,binarytreesare actuallyan extension of thelinked list structures.
10) Whichdatastructuresisappliedwhendealingwitharecursivefunction?

57
Recursion, which is basically a function that calls itself based on a terminating condition, makes use of
thestack. Using LIFO, a call to a recursive function saves the return address so that it knows how to return to
thecallingfunction after the call terminates.
11) Whatisastack?
A stack is a data structure in which only the top element can be accessed. As data is stored in the stack,
eachdatais pushed downward, leavingthemost recentlyadded data on top.
12) ExplainBinarySearchTree
A binary search tree stores data in such a way that they can be retrieved very efficiently. The left
subtreecontains nodes whose keys are less than the node‟s key value, while the right subtree contains nodes
whosekeysaregreater thanor equal tothenode‟s keyvalue. Moreover,bothsubtrees arealso binarysearchtrees.
13) Whatare multidimensionalarrays?
Multidimensional arrays make use of multiple indexes to store data. It is useful when storing data that
cannotbe represented using a single dimensional indexing, such as data representation in a board game, tables
withdatastored in morethanonecolumn.
14) Arelinkedlistsconsideredlinearornon-lineardatastructures?
It actually depends on where you intend to apply linked lists. If you based it on storage, a linked list
isconsidered non-linear. On the other hand, if you based it on access strategies, then a linked list is
consideredlinear.
15) Howdoesdynamicmemoryallocationhelpin managingdata?
Aside frombeing abletostore simple structureddata types,dynamicmemory
allocationcancombineseparatelyallocated structuredblocks toform composite structuresthat
expandandcontract asneeded.
16) WhatisFIFO?
FIFO is short for First-in, First-out, and is used to represent how data is accessed in a queue. Data has
beeninsertedinto thequeuelist thelongest is the onethat is removed first.

17) Whatisan orderedlist?


An ordered list is a list in which each node‟s position in the list is determined by the value of its
keycomponent,so that thekeyvalues forman increasingsequence,asthe list is traversed.
18) Whatis mergesort?
Merge sort takes a divide-and-conquer approach to sorting data. In a sequence of data, adjacent ones
aremerged and sorted to create bigger sorted lists. These sorted lists are then merged again to form an
evenbiggersorted list, whichcontinuous untilyou haveonesingle sorted list.
19) DifferentiateNULLandVOID.
Null is actually a value, whereas Void is a data type identifier. A variable that is given a Null
valuesimplyindicates anemptyvalue. Void is usedto identifypointers as havingno initial size.
58
20) Whatistheprimaryadvantageof alinkedlist?

A linked list is a very ideal data structure because it can be modified easily. This means that modifying
alinkedlist works regardless of howmanyelementsarein thelist.
21) Whatisthedifferencebetweena PUSHandaPOP?
Pushing and popping applies to the way data is stored and retrieved in a stack. A push denotes data
beingadded to it, meaning data is being “pushed” into the stack. On the other hand, a popdenotes data
retrieval,andin particular refers tothe topmost data beingaccessed.
22) Whatisalinearsearch?
A linear search refers to the way a target key is being searched in a sequential data structure. Using
thismethod, each element in the list is checked and compared against the target key, and isrepeated until
foundorif theend ofthe list has been reached.
23) Howdoesvariabledeclarationaffectmemoryallocation?
The amount of memory to be allocated or reserved would depend on the data type of the variable
beingdeclared. For example, if a variable is declared to be of integer type, then 32 bits of memory storage
will bereservedforthat variable.
24) Whatis theadvantageof theheap overa stack?
Basically, the heap is more flexible than the stack. That‟s because memory space for the heap can
bedynamically allocated and de-allocated as needed. However, memory of the heap can at timesbe
slowerwhencompared to that stack.
25) Whatisapostfixexpression?
A postfix expression is an expression in which each operator follows its operands. The advantage of this
formisthat thereisno needtogroupsub-expressionsin parentheses orto consider operatorprecedence.
26) WhatisthedifferencebetweentheHEAPandtheSTACK?
(Solution: HEAP is used to store dynamically allocated memory (malloc). STACK stores static
data(int, const).)
27) WhereinmemoryareHEAPandtheSTACKlocatedrelativetotheexecutingprogram?
(Solution:The STACKandHEAParestored"below"theexecutingprogram.TheHEAP"grows"
towardtheprogramexecutablewhile theSTACK grows awayfrom it.)
28) Describethedatastructuresof adouble-linkedlist.
(Solution:A double-linkedliststructurecontainsone pointer tothe previousrecordinthe listandapointer
tothenextrecord in thelist plus therecord data.)
29) Howdoyouinsertarecordbetweentwonodesin double-linkedlist?
(Solution:Previous R;Data R;Next R;To insertarecord(B)between twoothers(Aand C):Previous.B
=A;Next.B=C; Next.A =B;Previous.C=B;)
30) In which data structure, elements can be added or removed at either end, but not in
themiddle?
59
(Solution:queue)
31) Which one is faster? A binary search of an orderd set of elements in an array or
asequentialsearch oftheelements.
(Solution:binarysearch)
32) Whatisabalancedtree?
(Solution: A binary tree is balanced if the depth of two subtrees of every node never differ by
morethanone)
33) Whichdatastructureisneeded toconvertinfixnotationstopost fixnotations?
(Solution:stack)
34) Whatisdatastructureorhowwould youdefinedatastructure?
(Solution: In programming the term data structure refers to a scheme for organizing related
pieceofinformation. Data Structure=Organized Data+Allowed Operations.)
35) Whichdatastructureswecanimplementusinglinklist?
(Solution:queueand stack)
36) Listdifferenttypesofdatastructures?
(Solution:Linklist,queue,stack,trees,files, graphs)
37) Definealinearandnonlineardatastructure.
Linear data structure: A linear data structure traverses the data elements sequentially, in which only one
dataelementcan directlybereached. Ex: Arrays,LinkedLists
Non-Linear data structure: Every data item is attached to several other data items in a way that is specific
forreflectingrelationships. Thedata items arenot arrangedin a sequentialstructure. Ex:Trees, Graphs
38) Defineastack?
Ans: Stack is an ordered collection of elements. Insertion and deletion of stack is done only from one
end,calledtop ofthestack.Itis also called LIFO(Lastin firstout)
39) ExplainaQueue?
Ans: Queues are first in first out type(FIFO). New elements are added to the one end called REAR and
theelements are removed from the other end is called FRONT. The people standing in railway reservation
queueisa practical exampleof queue
40) Whatarethedifferent typesofqueuesavailable?
Ans:LinearQueue,CircularQueue,PriorityQueue
41) Whatisthe maindifferencebetweenastackand aqueue
Ans: Stack is LIFO and queue is FIFO. In stack insertion and deletion happening from one end(top of
thestack). But in Queue neew elements are added to the one end called REAR and the elements are
removedfromtheotherend iscalledFRONT.

60
ContentBeyondSyllabus
1) /* program swaps the nodes of linked list
ratherthanswappingthefieldfromthenodes.*/

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

/* A linked list node


*/structNode
{
intdata;
structNode*next;
};

/* Function to swap nodes x and y in linked list


bychanginglinks */
voidswapNodes(structNode**head_ref,intx,inty)
{
// Nothing to do if x and y are
sameif(x==y)return;

// Search for x (keep track of prevX and


CurrXstructNode*prevX=NULL,*currX=*head_ref;whil
e(currX&&currX->data!=x)
{
prevX=currX;
currX=currX->next;
}

// Search for y (keep track of prevY and


CurrYstructNode*prevY=NULL,*currY=*head_ref;whil
e(currY&&currY->data!=y)
{
prevY=currY;
currY=currY->next;
}

// If either x or y is not present, nothing to


doif(currX==NULL||currY==NULL)
return;

// If x is not head of linked


listif(prevX!=NULL)
prevX->next=currY;
else//Elsemakeyasnewhead
*head_ref=currY;

// If y is not head of linked


listif(prevY!=NULL)
prevY->next=currX;
else//Elsemakexasnewhead
*head_ref=currX;

//Swapnextpointers
structNode*temp=currY-
>next;currY->next = currX-
>next;currX->next= temp;
}

/* Function to add a node at the beginning of List


*/voidpush(structNode**head_ref,intnew_data)
61
{
/* allocate node
*/structNode*new_node=
(structNode*)malloc(sizeof(structNode));

/* put in the
data*/new_node-
>data=new_data;

/* link the old list off the new node


*/new_node->next=(*head_ref);

/* move the head to point to the new node


*/(*head_ref) =new_node;
}

/* Function to print nodes in a given linked list


*/voidprintList(structNode*node)
{
while(node!=NULL)
{
printf("%d ", node-
>data);node=node->next;
}
}

/* Driver program to test above function


*/intmain()
{
structNode*start=NULL;

/*Theconstructedlinkedlistis:
1->2->3->4->5->6->7*/
push(&start,7);
push(&start,6);
push(&start,5);
push(&start,4);
push(&start,3);
push(&start,2);
push(&start,1);

printf("\n Linked list before calling swapNodes()


");printList(start);

swapNodes(&start,4,3);

printf("\n Linked list after calling swapNodes()


");printList(start);

return0;
}

Output:
LinkedlistbeforecallingswapNodes() 1234567
LinkedlistaftercallingswapNodes()1243567

2) /* Program to implement a stack that supports findMiddle()


anddeleteMiddle inO(1) time */
#include <stdio.h>
#include<stdlib.h
62
/* A Doubly Linked List Node
*/structDLLNode
{
structDLLNode*prev;intda
ta;
structDLLNode*next;
};

/* Representation of the stack data structure that


supportsfindMiddle()
in O(1) time.The Stack is implemented using Doubly
LinkedList.It
maintainspointertoheadnode,pointertomiddlenodeandcount
of
nodes*/
structmyStack
{
structDLLNode*head;str
uct
DLLNode*mid;intcount;
};

/* Function to create the stack data structure


*/structmyStack*createMyStack()
{
structmyStack*ms=
(structmyStack*)malloc(sizeof(structmyStack));ms-
>count= 0;
returnms;
};

/* Function to push an element to the stack


*/voidpush(structmyStack*ms,intnew_data)
{
/* allocate DLLNode and put in data
*/structDLLNode*new_DLLNode=
(structDLLNode*)malloc(sizeof(structDLLNode));new_
DLLNode->data=new_data;

/* Since we are adding at the


beginning,previs alwaysNULL */
new_DLLNode->prev=NULL;

/* link the old list off the new DLLNode


*/new_DLLNode->next=ms->head;

/* Increment count of items in stack


*/ms->count+= 1;

/*Changemidpointerintwocases
1) LinkedListisempty
2) Number of nodes in linked list is odd
*/if(ms->count==1)
{
ms->mid=new_DLLNode;
}
else
{
ms->head->prev=new_DLLNode;

if(ms->count&1)//Updatemidifms->countisoddms->mid=
ms->mid->prev;
63
}

/* move head to point to the new DLLNode


*/ms->head=new_DLLNode;
}

/* Function to pop an element from stack


*/intpop(structmyStack*ms)
{
/* Stack underflow
*/if(ms->count==0)
{
printf("Stack is
empty\n");return-1;
}

structDLLNode*head=ms-
>head;intitem=head->data;
ms->head=head->next;

//Iflinkedlistdoesn'tbecomeempty,updateprev
// of new head as
NULLif(ms->head!=NULL)
ms->head->prev =

NULL;ms->count-= 1;

//updatethemidpointerwhenwehaveevennumberof
// elements in the stack, i,e move down the mid
pointer.if(!((ms->count)&1))
ms->mid = ms->mid-

>next;free(head);

returnitem;
}

// Function for finding middle of the


stackintfindMiddle(structmyStack*ms)
{
if(ms->count==0)
{
printf("Stack is empty
now\n");return-1;
}

returnms->mid->data;
}

// Driver program to test functions of


myStackintmain()
{
/* Let us create a stack using push()
operation*/structmyStack*ms=createMyStack();
push(ms,11);
push(ms,22);
push(ms,33);
push(ms,44);
push(ms,55);
push(ms,66);
push(ms,77);

64
printf("Item popped is %d\n",
pop(ms));printf("Item popped is %d\n",
pop(ms));printf("Middle Element is %d\n",
findMiddle(ms));return0;
}

Output:
Itempoppedis77Ite
mpoppedis66
MiddleElementis33

65
66
Vision statement of the Institution

"To become a recognized world class Women Educational Institution, by


imparting professional education to the students, creating technical
opportunities through academic excellence and technical achievements, with
ethical values"

Mission statement of the Institution

o To support value based education with state of art infrastructure.

o To empower women with the additional skill for professional future


carrier

o To enrich students with research blends in order to fulfill the


International challenges

o To create multidisciplinary center of excellence

o To achieve Accreditation standards towards intentional education


recognition.

o To establish more Post Graduate & Research course.

o To increase Doctorates numbers towards the Research quality of


academics.

You might also like