Download Data Structure - knowledgebounce

Document related concepts

Array data structure wikipedia , lookup

Lattice model (finance) wikipedia , lookup

Red–black tree wikipedia , lookup

Linked list wikipedia , lookup

Quadtree wikipedia , lookup

B-tree wikipedia , lookup

Interval tree wikipedia , lookup

Binary tree wikipedia , lookup

Binary search tree wikipedia , lookup

Transcript
SUBJECT: DATA STRUCTURE
Section – A
[QUESTIONS 1 TO 29]
1/63
2 Marks Questions
Q1.
Ans.
What is data structure?
A data structure defines the way data is stored in computer two types of data
structures are:
 Linear
 Non-linear
The logical or mathematical model of a particular organization of data is called a data
structure. It is used for storing information in memory.
Q2.
Ans.
What are two main types of data structure?
1.Linear Data Structure:
A data structure is said be linear if its elements are stored sequentially in the
form of a linear list e.g. arrays, stacks, linked lists.
2. Non-linear Data structure:
A data structure is said to be non-linear if its elements are not stored
sequentially e.g. trees & graphs.
Q3.
Ans.
Write various operations performed on data structure.
The various operations are: 1. Traversing
2. Inserting
3. Deleting
4. Merging
5. Searching
6. Sorting
7. Updating
8. Creating
Q4.
Ans.
What is an array? How array is stored in memory.
Arrays are subscripted variables. Array is collection of homogeneous data elements.
They are stored in continuous memory locations. They are accessed by using index
value.
int a[5];
12
4
45
67
68
1000
1002
1004
1006
1008
1000 is the location of the first element of the array. As the int data type takes two
bytes of the memory in ‘c’ language so the next element is stored at 1002 and so on.
Q5.
Ans.
What are pointer Arrays?
A pointer array is memory variable that use to store address of a variable. Pointer
arrays are use to store address of more then one variable. Pointer arrays are also
called arrays of pointers.
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],*p[10],i;
for(i=0;i<10;i++)
{
p[i]=&a[i];
}
SUBJECT: DATA STRUCTURE
2/63
for(i=0;i<10;i++)
{
printf("%d\n",p[i]);
}
getch();
}
Q6.
Ans.
What is a linked list?
A linked list or one-way list is a linear collection of data elements, called nodes,
where the linear order is given by means of pointers.
Each node is divided into 2 parts. The first part contains the information of the
element & the second part called the link field, contains the address of the next node
in the list.
Data
link
Node
Q7.
Ans.
Write syntax to declare a node of linked list.
Singly linked list
struct node
{
int info;
struct node *link;
};
Doubly linked list
Struct node
{
struct node *next;
int info;
struct node *prev;
};
Q8.
Ans.
Name some different types of linked list?
The various types of linked list are:1. Singly
2. Doubly
3. Circular
4. Reversible
Q9.
Ans.
What are Reversible linked list?
A reversible linked list enable you to visit a node, Which is previously visited by the
pointer, we can visit any node, which is previously visited, By providing address of
the node.
Q10.
Ans.
What are operations performed on linked list?
1. Insertion
2. Deletion
3. Searching
5. Traversing
Q11.
Write an algorithm to delete a node from the beginning of the linked list.
Ans.
DeleteFirst
SUBJECT: DATA STRUCTURE
3/63
1) If START==NULL
a) write “Underflow”
b) exit
2) Start =Start->link
3)Exit
Q12.
Write an algorithm to delete a node from the END of the linked list .
Ans. DeleteEnd
1)If START == NULL
a) Write “Underflow”
b) Exit
2)Set Temp=Start
3) While temp->link!=NULL
a) temp=temp->link
4)Set Temp=NULL
5) Exit
Q13.
Write a function to insert in a linked list at the first position.
Ans.
void add_beg(struct node **q,int num)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
temp->link=*q;
*q=temp;
}
Q14
Write a function to delete from a linked list.
Ans.
void del(struct node **q, int num)
{
struct node *old, *temp;
temp=*q;
while(temp!=NULL)
{
if(temp->data==num)
{
if(temp==*q)
*q=temp->link;
else
old->link=temp->link;
free(temp);
return;
}
else
{
old=temp;
temp=temp->link;
}
}
SUBJECT: DATA STRUCTURE
4/63
printf("Element not found");
}
Q15
Write a function to print elements from a linked list.
Ans.
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->link;
}
}
Q16
Ans.
Define Header linked list.
A header-linked list is a linked list, which always contains a special node called the
header node, at the beginning of the list.
TYPES
1.Gounded header list:-In this, last node contain the null pointer.
2.Circular header list:- in this, last node points back to the header node.
Q17.
Ans.
Differentiate between local & global variables.
Local variables: are those variables, which are available to only some parts of the
program. Their scope is limited to their block. Any changes made to them are not
visible outside their block
Global variables: are those variables, which are available throughout the program
and any changes made to them are visible globally.
Q18.
Ans.
Differentiate between structured & modular programming.
Structured programming considers the problem as a single structure & applies the
various conventional methods to solve that problem. On the other hand, modular
programming divides the main module into a number of different sub modules. Then
the main module refers to a number of subordinate modules
Q19.
Ans.
Define Circular linked list.
In circular linked list the last node stores the address of the first node.
SUBJECT: DATA STRUCTURE
Q 20.
Ans.




5/63
What are advantages of arrays over Linked list?
Advantages of arrays are
Data access is faster in Arrays.
Arrays are easier to implement
There is no need to specify the pointer field in arrays
It is possible to iterate through arrays
Q 21. How will you test Queue for underflow?
Ans. Queue underflow means deleting an item from queue when the queue is already
empty. This condition is called underflow. We can test it by checking if the queue is
empty (rear= -1).
Q 22. Write the applications of stacks.
Ans. Applications Of Stacks:
 Recursion Call
 Interrupt Handling
 Traversing in Graph (Depth First Search)
 Infix to postfix
 Postfix evaluation
Q 23. How do you initialize an array
Ans. Initialize means giving values at the time of declaring.
When we initialize an array, we give values to its elements when we declare it.
Syntax is:
Datatype arrayname[] = {value1, value2,….};
Example:
int arr[5] = {3,2,5,7,9};
Here, we created an array of 5 integers, and supplied the elements at the time of
decleration.
We can also write it as:
int arr[] = {3,2,5,7,9}; without mentioning the subscript
Q 24. What are the advantages of linked lists over arrays?
Ans. Arrays require that all the elements of the array should be stored in contiguous
memory locations. This requires a large chunk of memory. Such a large chunk of
memory might not be available at all times. Whereas linked list elements can be
stored at different locations in memory. Which makes memory allocation easier.
Q 25. What is a pointer? How can you declare a pointer to a structure?
Ans. A pointer is a special variable which stores the address of another variable. A pointer
to a structure holds the address of a structure object. The operator for pointer to
object is ->
For example:
Struct student
{
SUBJECT: DATA STRUCTURE
6/63
char name
};
struct student *s1;
Q 26. If we always make insertions and deletions only at the start of a linked list, then
which data structure it will represent?
Ans. It will represent a stack, because in stacks, insertions and deletions take place at the
top of stack.
Q 27
Ans.
What is recursion? What are its applications?
Recursion is the process in which a function calls itself. There are many applications
of stacks. Some of the applications are:
Tree traversal: tree traversal can be done efficiently and easily with the help of
recursion
Towers of Hanoi: this problem can not be solved without using recursion.
Q 28
Ans.
What is a pointer variable? What operations are possible on pointer variables?
A pointer is a special variable which holds the address of another variable. Different
operations possible on pointer variables are:
1) Addition of a number to a pointer
2) Subtraction of a number from a pointer
3) Subtraction of two pointers
Q 29
Ans.
How can you declare array of structures? Give one example.
An array of structures can be declared similar to an array of ordinary variables.
Example: struct student
{
int roll;
char name;
};
struct student s[10];
Section – A
[QUESTIONS 1 TO 25]
Q1.
Ans.
5 Marks Questions
How to declare an array?
Datatype arrayname[size]
(1) An array must be declared since it is a type of variable.
(2) An array containing five elements all of which are integers can be declared as
follows:
int x[5];
(3) The name of the array can not be same as that of any other variable declared
within the function.
(4) The size of the array (the no of elements ) specified using the subscript notation.
(5) The subscript 5 indicates how many elements are to be allocated to array x
(6) The subscript used to declare an array are called dimension.
The elements of five element array in c are numbered starting with 0 not with 1.
E.g. Suppose we want to store nos. 12,32,15,43,9 then the assignment statement for
this should be as under
int x[] ={12,32,15,43,9};
Q2.
This is called initialization
Write a program to input and print numbers using array.
SUBJECT: DATA STRUCTURE
7/63
Ans.
#include<stdio.h>
Q3.
void main()
{
int i,s[10];
for(i=0;i<10;i++)
{
scanf("%d",&s[i]);
}
for(i=0;i<10;i++)
{
printf("\n %d",s[i]);
}
}
Write a program to input and print characters(string) using array.
Ans.
#include<stdio.h>
void main()
{
int I;
char s[10];
scanf("%s”,&s);
printf("%s",s);
}
Q4.
Ans.
Q5.
Ans.
Write a program to input marks in 4 subjects of 10 students and print.
#include<stdio.h>
void main( )
{
int a[10][4],i,j;
clrscr( );
printf(“enter data\n”);
for(i=0;i<10;i++)
{
for(j=0;j<4;j++)
{
scanf("%d",&a[i][j]);
}
}
printf(“Details are\n”);
for(i=0;i<10;i++)
{
for (j=0;j<4;j++)
{
printf("\n %d ",a[i][j]);
}
}
getch( );
}
Create a program to print the transpose of a matrix.
void main()
{
int a[3][3],i,j;
printf(“enter the values\n”);
for(i=0;i<3;i++)
SUBJECT: DATA STRUCTURE
Q6.
Ans.
8/63
{ for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d ”,a[j][i]);
}
printf(“\n”);
}
getch();
}
Write a program for multiplication of two 2-D arrays.
#include<stdio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
printf (“Enter first matrix”\n);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
printf(Enter second matrix “\n)
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
scanf(“%d”,&b[i][j]);
}
for (i=0;i<3,i++)
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<r2;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
printf (“Result of Multiplication\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d”,c[i][j]);
}
printf(“\n”);
Q7.
Ans.
}
Write a program for addition of two 2-D array.
#include<stdio.h>
void main()
SUBJECT: DATA STRUCTURE
9/63
{
int a[2][2],b[2][2],c[2][2];
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
for( i=0;i<2;i++)
{
for( j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
}
}
for( i=0;i<2;i++)
{
for( j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for( i=0;i<2;i++)
{
for( j=0;j<2;j++)
{
printf("%d ",c[i][j]);
}
printf("\n ");
}
getch();
}
Q8.
What do you mean by call by reference?
Ans.
In this approach the addresses of the actual arguments are passed to the called
function. In this way processing is done on the addresses of the variables, so any
changes made are visible outside.
#include<stdio.h>
void add(int*,int*);
void main()
{int a,b;
a=10;
b=20;
add(&a,&b);
printf("%d %d",a,b);
}
void add(int *a, int *b)
{
*a=*a+1;
*b=*b+1;
}
Q9.
Create a program to print the transpose of a matrix using function.
Ans.
void trans(int[ ]);
void main()
SUBJECT: DATA STRUCTURE
10/63
{
int a[2][2],I,j;
printf(“Enter elements\n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&a[I][j]);
}
}
trans(a);
}
void trans(int a[ ])
{
int I,,j;
for(I=0;I<2;I++)
{
for(j=0;j<2;j++)
{
printf(“\t%d”,a[j][I]);
}
printf(“\n”);
}
getch();
}
Q10.
Ans.
What is a doubly linked list?
A doubly linked list is a linked list where every node is divided in three parts:
Left pointer
Right pointer
Information field
The left pointer points to the previous node
Information field contains the data
The right pointer points to the next node
Q11.
Ans.
Discuss the advantages & disadvantages of circular linked list.
Circular lists have certain advantages over singly linked list. The first advantage is
that in a circular list every node is accessible from a given node.
A second advantage is concerned with the deletion operation. In order to delete a
node in a singly linked list, it is necessary to give the address of the first node of the
list. This is necessary because we need to find the predecessor of the node to be
deleted To find the predecessor of a search is required starting from the first node of
the list. In the case of circular list, this requirement does not exist since the search for
the processor of the node to be deleted can be initiated from that node itself.
However, there is a disadvantage in using circular lists. It is possible to get into an
infinite loop. In processing a circular list, it is important that we are able to detect the
end of the list.
Q12.
Write an algorithm to create a linked list & insert an item into a linked list in
beginning.
Ans.
InsertFirst
1. If list = full
SUBJECT: DATA STRUCTURE
2.
3.
4.
5.
6.
11/63
a) Write “overflow”
b)Exit
Set memory for new node
Set new->info=item
Set new->link=start
Set start=new
Exit.
Q13.
Ans.
Write an algorithm to insert an item into a linked list in end.
InsertEnd
1. If list==full
a)Write “overflow”
b)Exit
2. Set memory fro the new node
3. Set new->info=item.
4. Set new->link=null
5. temp=start
6. while temp!=null
temp=temp->link
7. Set temp = new .
8. Exit.
Q14.
Ans.
Write a program to pass structure in function using pointer.
#include<stdio.h>
#include<conio.h>
struct emp
{
char empname[34];
int empno;
int bs;
int bonus;
float total;
};
void print(emp*);
void main()
{
int i;
clrscr();
emp k;
printf("enter");
scanf("%s%d%d",&k.empname,&k.empno,&k.bs);
print(&k);
}
void print(emp *k)
{
k->bonus=k->bs/10 ;
k->total=(float)k->bs+k->bonus;
printf("\nemployee name is \t %s sal=\t%f",k->empname,k->total);
}
Q15.
Ans.
Write a program to pass array in function using pointer.
#include<stdio.h>
#include<conio.h>
void print(int*);
void main()
SUBJECT: DATA STRUCTURE
12/63
{
int a[5],i;
clrscr();
printf("enter numbers");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
print(a);
getch();
}
void print(int *p)
{
int i;
for(i=0;i<5;i++)
{
printf("%d ",p[i]);
}
Q16
Ans.
1.
2.
3.
4.
5.
What are the advantages of using pointers ?
Q17.
Ans.
Write a program to implement linked list using functions.
//linked list using functions
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
void add_end(struct node **q, int num)
{
struct node *temp,*r;
if(*q==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
temp->link=NULL;
*q=temp;
}
else
{
temp=*q;
while(temp->link!=NULL)
{
It supports dynamic allocation/ deallocation of memory.
It provides various functions to modify their calling arguments.
It allows to pass arrays, functions as function arguments.
Pointers helps in improving the efficiency of certain routines.
Pointers helps in swapping the variables without their physical movement.
SUBJECT: DATA STRUCTURE
13/63
temp=temp->link;
}
r=(struct node*)malloc(sizeof(struct node));
r->data=num;
r->link=NULL;
temp->link=r;
}
}
void add_beg(struct node **q,int num)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
temp->link=*q;
*q=temp;
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->link;
}
}
void del(struct node **q, int num)
{
struct node *old, *temp;
temp=*q;
while(temp!=NULL)
{
if(temp->data==num)
{
if(temp==*q)
*q=temp->link;
else
old->link=temp->link;
free(temp);
return;
}
else
{
old=temp;
temp=temp->link;
}
}
printf("Element not found");
}
void main()
{
struct node *p;
clrscr();
p=NULL;
add_end(&p,14);
add_end(&p,23);
SUBJECT: DATA STRUCTURE
Q18.
14/63
add_end(&p,67);
display(p);
add_beg(&p,89);
display(p);
del(&p,23);
display(p);
getch();
}
Write a program to implement doubly (two–way) linked list.
Ans. #include<stdio.h>
#include<conio.h>
struct node
{
struct node *prev;
int data;
struct node *next;
};
void add(struct node **s, int num)
{
struct node *q;
q=(struct node*)malloc(sizeof(struct node));
q->prev=NULL;
q->data=num;
q->next=*s;
(*s)->prev=q;
*s=q;
}
void del(struct node **s, int loc)
{
struct node *current;
int item;
if((*s)==NULL)
{
printf(“List Empty”);
}
else
{
current = (*s);
if(loc==1)
{
item=current->data;
(*s)=(*s)->next;
if((*s)!=NULL)
(*s)->prev=NULL;
free(current);
return;
}
else
{
for(i=2;i<=loc;i++)
{
current = current->next;
if(current==NULL)
{
printf(“Insufficient nodes”);
SUBJECT: DATA STRUCTURE
15/63
return();
}
}
current->prev->next = current->next;
if(current->next!=NULL)
current->next->prev = current->prev;
item=current->data;
free(current);
return;
}
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->next;
}
}
void main()
{
struct node *p;
p=NULL;
add(&p,33);
add(&p,12);
add(&p,9);
display(p);
del(&p,12);
display(p);
getch();
}
Q.19
Ans.



Write an algorithm to delete a node N with a given location from a two-way list.
A two-way list is a linear collection of data elements, called nodes, where each node
N is divided into three parts.
An information field INFO, which contains the data of N
A pointer field FORW, which contains the location of the next node in the list
A pointer field BACK, which contains the location of the preceding node in the list
Suppose we are given the location LOC of a node N in LIST, and suppose we want to
delete N from the list. We assume that LIST is a two-way circular header list. BACK[LOC]
and FORW[LOC] are the locations of the nodes which precede and follow node N.
Algorithm is:
DeleteNode
1. Set loc->back->forw :=loc->forw
loc->forw->back := loc->back
2. Set loc->forw := free and loc=avail
3. Exit.
SUBJECT: DATA STRUCTURE
16/63
Q20
Write a function to delete a node N with a given location from a two-way list.
Ans. void del(struct node **s, int loc)
{
struct node *current;
int item;
if((*s)==NULL)
{
printf(“List Empty”);
}
else
{
current = (*s);
if(loc==1)
{
item=current->data;
(*s)=(*s)->next;
if((*s)!=NULL)
(*s)->prev=NULL;
free(current);
return;
}
else
{
for(i=2;i<=loc;i++)
{
current = current->next;
if(current==NULL)
{
printf(“Insufficient nodes”);
return();
}
}
current->prev->next = current->next;
if(current->next!=NULL)
current->next->prev = current->prev;
item=current->data;
free(current);
return;
}
}
Q.21
Consider the following DEQUE with 6 memory cells
LEFT=2
RIGHT=2
DEQUE: _, A, C, D, _, _
Describe the deque while the following operations take place:
a)
b)
c)
d)
F is added to the right of the deque.
Two letters on the right are deleted.
K,L and M are added to the left of the deque
One letter on the left is deleted
SUBJECT: DATA STRUCTURE
17/63
Ans.
a) F is added to the right:
LEFT = 2, RIGHT= 5, DEQUE = _, A, C, D, F, _
b) Two letter from right (F and D) are deleted
LEFT = 2, RIGHT = 3 DEQUE = _, A, C, _, _, _
c) K, L and M are added to the left
LEFT =5, RIGHT= 3, DEQUE = K, A, C, _, M, L
d) First letter (M) is deleted
LEFT = 6, RIGHT = 3, DEQUE = K, A, C, _, _, L
Q. 22 Explain the difference between Call by Value and Call by Reference with the
help of an example.
Ans.
/* call by value */
void main()
{
int a=10;
int b=20;
add(a,b);
printf(“a=%d”,a);
printf(“b=%d”,b);
}
void add(int a, int b)
{
a=a+1;
b=b+1;
printf(“a is %d”,a);
printf(“b is %d”,b);
}
Output:
a=10
b=20
a=10
b=20
/* call by reference */
void main()
{
int a=10;
int b=20;
add(&a,&b);
printf(“a=%d”,a);
printf(“b=%d”,b);
}
void add(int *a, int *b)
{
*a= *a+1;
SUBJECT: DATA STRUCTURE
18/63
*b= *b+1;
}
Output:
a=20
b=10
Q 23. Write an algorithm to search an element KEY from a sorted linked list
Ans.
SEARCH
LIST is a linked list. We have to find the location LOC where KEY first appears. If not
found, set LOC=NULL
1. Set PTR=START
2. Repeat steps while PTR !=NULL
a) If KEY= PTR->INFO then
i.
Set LOC=PTR
ii.
Exit
b) Else
i.
Set PTR=PTR->LINK
3. Set LOC=NULL
4. Exit
Q 24. What are multidimensional arrays? Give example of some data for which a 3dimensional array is needed.
Ans. Multidimensional arrays are those arrays which have more than one
dimension, that is, more than one subscript.
Two dimensional array:
A 2-D array is an array which has got 2 subscripts.
Example: int arr[3][2];
Here, arr is a two dimensional array, with first subscript size of 3 and second
sunscript size of 2. this array can contain 3X2=6 elements
Three dimensional array:
A 3-D array is an array which has got 3 subscripts.
Example: int arr2[4][2][3];
Here arr2 is a 3-D array. The size of first subscript is 4, second is 2 and third is 3.
A two-dimensional array is used in case of matrices.
A three dimensional array is used in case of object modeling. It is used in designing
purposes.
Q 25. What are arrays of pointers? Explain its utility for storing two dimensional data.
Ans.
A array of pointers(pointer array) is memory variable that use to store address of a
variable. Pointer arrays are use to store address of more then one variable. Pointer
arrays are also called arrays of pointers.
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],*p[10],i;
for(i=0;i<10;i++)
{
SUBJECT: DATA STRUCTURE
19/63
p[i]=&a[i];
}
for(i=0;i<10;i++)
{
printf("%d\n",p[i]);
}
getch();
}
It can be used to store the base address of an array, which makes accessing data of
a two dimensional array easier.
Section – B
[QUESTIONS 1 TO 22]
2 Marks Questions
Q1.
Ans.
Define Stack.
It is also called Last-In-First-Out system. Is a linear list in which insertions and
deletions can take place only at one end, called top. It has got two operations.
Push: to insert an element
Pop: to delete an element
Q2.
Ans.
Define PUSH , POP.
Push:- It is the operation to insert an element in the stack. In this operation, top is
incremented by 1
Pop :- It is the operation to delete an element from the stack. In this operation, top is
decremented by 1
Q3.
Ans.
Name Operations Performed On Stacks.





Q4.
Ans.
Initialization of Stack.
Push Operation.
Pop Operation.
Underflow Operation.
Overflow Operation.
Write a Algorithm of Underflow Operation.
Underflow
1. if top[S] = -1
2. then return true
3. else return false
Q5
Write a Algorithm of Overflow Operation.
Ans. Overflow
4. if top[s] is equal to last available location
5. then return true
6. else return false
Q6.
Ans.
Write a Algorithm of Push operation.
Push
1)If TOP=max Then
a)Write “over flow”
b)exit
2)TOP=TOP+1
SUBJECT: DATA STRUCTURE
20/63
3)Stack[top]=item
4)Exit
Q7.
Ans.
Write a Algorithm of POP Operation
POP
1. If TOP=-1 Then
a)Write “ Underflow”
b)Exit
2. TOP=TOP -1
3. Exit
Q8. Write Applications Of Stacks.
Ans.
 Recursion Call
 Interrupt Handling
 Traversing in Graph (Depth First Search)
 Infix to postfix
 Postfix evaluation
 Checking validity of an expression
Q9.
Ans.
What is time & space complexity?
Time complexity is related to the performance requirements of an algorithm.
Space complexity is the amount of memory it needs to run to completion. It means
the memory taken by an algorithm.
Q10. Write difference between stack and queue.
Ans. Queues
Queues are FIFO linear structures Queues are used for a variety of purposes and
implemented in multiple ways. Example priority queues. Not used in recursion
Stacks
Stacks are LIFO structures. Stacks cannot be implemented in a variety of ways.
Used in recursion
Q11.
Ans.
What is Queue?
Queue is also called First-In First Out system, it is a linear list in which insertions take
place at one end known as rear and deletions can take place from the other end
known as front.
Q12.
Ans.
Name different types of Queue.




Q13.
Ans.
Simple Queue
Circular Queue
Priority Queue
Deques(Double ended queues)
Write Various operations performed on Queue.
Operations Performed On Queues:
 Initialization of Queue
 Insertion of element
 Deletion of element
 Overflow operation
 Underflow operation
SUBJECT: DATA STRUCTURE
Q14.
Ans.
21/63
Write algorithm to Insert in a queue.
This operation increments the rear by one and stores the element at new position of
rear.
Insert
1. If rear==max
a) Write “overflow
b) Exit.
2. rear = rear+ 1
3. Q [rear] = item
4. Exit
Q15. Write algorithm to delete an element from Queue.
Ans. This operation will remove the first element from the queue Q.
Delete
1) If rear==-1
a) Write “under flow”
b) Exit.
2)If rear==front
a) Set Rear=-1
b) Set Front=-1
c) Exit
3)front=front + 1
4) Exit
Q16.
Ans.
Define Priority Queue.
A priority queue is a collection of elements such that each elements has been
assigned a priority and such that the order in which elements are deleted and
processed comes from the following rules:
1. An element of higher priority is processed before any element of lower
priority.
2. Two elements with the same priority are processed according to the order in
which they were added to the queue.
Q17.
Ans.
Write Applications of Queues.
One of the important areas to which queues can be applied is that of simulation. It is
the process of forming an abstract model from a real situation in order to understand
the impact of modifications & the effect of introducing various strategies on the
situation. The major advantage of simulation is that it allows experimentation without
modifying the real situation. Areas such as military operations are safer to simulate.
Q18.
Ans.
What is dequeue?
A dequeue also known as double ended queue. It is a link of queues in which
elements can be added or removed from at either end but not in the middle. Two
types of deques are:
i) input restricted deque
ii) output restricted deque
Q 19. What are sparse matrices?
Ans. Matrices with a relatively high proportion of 0’s are called sparse matrices. In
mathematical terms, sparse matrix is a matrix populated primarily with zeros. There
are two types of n-square sparse matrices.
1. Lower triangular matrix
2. Tridiagonal matrix
Q.20 Write a note on reverse linked list.
SUBJECT: DATA STRUCTURE
22/63
Ans. Reversing a linked list is the process of reversing the order of the linked list.
After reversing the linked list, the first element becomes the last, the last becomes
the first and so on. The resultant list after the reversing process is called the reversed
linked list
Q 21. Why there is need for so many searching and sorting algorithms?
Ans. There is a need for searching algorithm to search a particular item from a list of
elements. For example, If a list is large and sorted, we should use binary searching
instead of linear search as it saves time.
In case of sorting, we should choose an algorithm that best suits our requirements
Selecting a searching and sorting algorithm depends upon the complexity and timeefficiency of the algorithm
Q 22. What are the various techniques to implement queues?
Ans. There are tow ways to implement queues. One is the array representation, and other
is the linked representation. Array implementation is easier to follow, but linked
representation is more efficient.
Section – B
[QUESTIONS 1 TO 27]
5 Marks Questions
Q1.
Ans.
Explain Prefix Expression With Examples.
Infix expression can be written in prefix form as + A B. Prefix form is also known as
Polish Notation.
To convert infix to prefix 3 levels of precedence are used
Highest : Exponentiation (^)
Next Highest : Multiplication (*) & Division (/)
Lowest : Addition (+) & Subtraction ( - )
Eg 1
(A + B) * C
(+ A B) * C
*+ABC
Eg2.
(A + B) / (C - D)
(+ AB) / (-C D)
/+AB–CD
Q2.
Ans.
Explain of Postfix Expression with Examples.
Infix expression can be written in postfix form as A B +.Postfix expression also known
as Reverse polish notation.
To convert infix to postfix 3-level level of precedence are used.
Highest : Exponentiation (^)
Next Highest : Multiplication (*) & Division (/)
Lowest : Addition (+) & Subtraction ( - )
Eg1.
(A + B) * C
( A + B +)* C
A B + C*
Eg2.
(A + B) / (C – D)
( A B +) / ( C D -)
AB+CD-/
Q3.
Write an algorithm for transforming infix expression into postfix expression
with example.
SUBJECT: DATA STRUCTURE
23/63
Ans. POLISH (Q, P)
Suppose Q is an arithmetic expression written in infix mutation. This algorithm finds
the equivalent postfix expression P.
1.
Push “(“ onto STACK & add) “ to the end of Q
2.
Scan Q from left to right & repeat steps 3 to 6 for each element of Q until the
stack is empty.
3.
If an operand is encountered, add it to P.
4.
If a left parenthesis”(“ is encountered, push it onto STACK.
5.
If an operator Q is encountered, then
a) Repeatedly pop from STACK & add to P each operator, which has the
same precedence as or higher precedence than Q.
b) Add Q to STACK
[End of If structure]
6.
If a right parenthesis “)” is encountered
a) Repeatedly pop from STACK & add to P each operator until a left
parenthesis is encountered.
b) Remove the left parenthesis [Do not add the left parenthesis to P]
[End of If structure]
[End of step 2 Loop]
7.
Exit
Q4.
Write a program to implement a stack.
Ans. #include<stdio.h>
#include<conio.h>
#define max 10
int top=-1;
int stack[max];
void push(int x)
{
if(top==max-1)
{
printf("Overflow");
exit();
}
top=top+1;
stack[top]=x;
}
void pop()
{
if(top==-1)
{
printf("Underflow");
exit();
}
top=top-1;
}
void display()
{
int i;
for(i=0;i<=top;i++)
{
printf("%d\n",stack[i]);
}
}
void main()
SUBJECT: DATA STRUCTURE
24/63
{
push(3);
push(56);
push(12);
display();
pop();
display();
getch();
}
Q6.
Write a program to implement linked list as stack(linked implementation of
stacks).
Ans.
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
void push(struct node **top,int num)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("Overflow");
exit();
}
temp->data=num;
temp->link=*top;
*top=temp;
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->link;
}
}
void pop(struct node **top)
{
struct node *temp;
if(top==NULL)
{
printf("Underflow");
exit();
}
temp=*top;
*top=(*top)->link;
free(temp);
}
void main()
SUBJECT: DATA STRUCTURE
25/63
{
Q7.
Ans.
struct node *p;
clrscr();
p=NULL;
push(&p,14);
push(&p,23);
push(&p,67);
display(p);
pop(&p);
display(p);
getch();
}
Explain Circular Queue.
A circular queue is a queue in which the front and rear are touching each other. It is
shaped in the form of a ring. Working of Circular Queue is given as
following:
SUBJECT: DATA STRUCTURE
26/63
Q8.
Ans.
Define Underflow and Overflow operations.
Underflow Operation
This algorithm is called before deleting an element and return true if queue is
empty else return false
Underflow
1.if rear = = -1
2.then return true
3.else retun false
4 exit
Overflow Operation
This algorithm is called before inserting an element to check whether a queue
is full or not. This algorithm will return true if queue is full else return false.
Overflow
1 If rear ==max
2 then return true
3 else return false
4 exit
Q9.
Ans.
Write a program to implement Queue.
#include<stdio.h>
#include<conio.h>
#define max 10
int front=-1;
int rear=-1;
int q[max];
void insertq(int x)
{
if(rear==max-1)
{
printf("Overflow");
exit();
}
rear=rear+1;
q[rear]=x;
}
void deleteq()
{
if(rear==-1)
{
printf("Underflow");
exit();
}
if(front==rear)
{
front=-1;
rear=-1;
exit();
}
front=front+1;
}
void display()
{
int i;
SUBJECT: DATA STRUCTURE
Q11.
27/63
for(i=front+1;i<=rear;i++)
{
printf("%d\n",q[i]);
}
}
void main()
{
clrscr();
insertq(23);
insertq(6);
insertq(21);
display();
deleteq();
display();
getch();
}
Write a program to implement Queue using linked list(linked representation of
queues).
Ans. #include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
void insertq(struct node **q, int num)
{
struct node *temp,*r;
if(*q==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("Overflow");
exit();
}
temp->data=num;
temp->link=NULL;
*q=temp;
}
else
{
temp=*q;
while(temp->link!=NULL)
{
temp=temp->link;
}
r=(struct node*)malloc(sizeof(struct node));
r->data=num;
r->link=NULL;
temp->link=r;
}
}
void delq(struct node **q)
{
SUBJECT: DATA STRUCTURE
28/63
struct node *temp;
if((*q)->link==NULL)
{
printf("Underflow");
exit();
}
temp=(*q)->link;
free(temp);
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->link;
}
}
void main()
{
struct node *p;
clrscr();
p=NULL;
insertq(&p,34);
insertq(&p,21);
insertq(&p,45);
display(p);
delq(&p);
display(p);
getch();
}
Q12.
Write a program to implement Circular Queue.
Ans.
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
void addcirq(struct node **f, struct node **r, int item)
{
struct node *q;
q=(struct node*)malloc(sizeof(struct node));
if(q==NULL)
{
printf("Overflow");
exit();
}
q->data=item;
if(*f==NULL)
*f=q;
else
SUBJECT: DATA STRUCTURE
29/63
(*r)->link=q;
*r=q;
(*r)->link=*f;
}
void delcirq(struct node **f, struct node **r)
{
struct node *q;
if(*f==NULL)
{
printf("Underflow");
exit();
}
else
{
if(*f==*r)
{
free(*f);
*f=NULL;
*r=NULL;
}
else
{
q=*f;
*f=(*f)->link;
(*r)->link=*f;
free(q);
}
}
}
void cirq_display(struct node *f)
{
struct node *q=f;
struct node *p=NULL;
while(q!=p)
{
printf("%d\n",q->data);
q=q->link;
p=f;
}
}
void main()
{
struct node *front,*rear;
clrscr();
front=rear=NULL;
addcirq(&front,&rear,10);
addcirq(&front,&rear,67);
addcirq(&front,&rear,2);
addcirq(&front,&rear,89);
cirq_display(front);
delcirq(&front,&rear);
cirq_display(front);
getch();
}
SUBJECT: DATA STRUCTURE
Q14.
Ans.
30/63
Write a program to convert infix to postfix.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char ie[20];
char pe[20];
char s[20];
int i,t=0,k=0,j=0;
clrscr();
scanf("%s",&ie);
printf("\noriginal exp=%s",ie);
i=strlen(ie);
ie[i]=NULL;
i=0;
while(ie[i]!=NULL)
{
if(ie[i]=='+'||ie[i]=='-'||ie[i]=='*'||ie[i]=='/')
{
if(t==0)
{
s[t]=ie[i];
t++;
}
else
{
if(ie[i]=='*'||ie[i]=='/')
{
s[t]=ie[i];
t++;
}
else
{
while(s[t-1]=='*'||s[t-1]=='/'||s[t-1]=='+'||s[t-1]=='-')
{
pe[k]=s[t-1];
k++;
t--;
}
s[t]=ie[i];
t++;
}
}
}
else
{
pe[k]=ie[i];
k++;
}
i++;
SUBJECT: DATA STRUCTURE
31/63
}
t--;
while(t!=-1)
{
pe[k++]=s[t--];
}
pe[k]='\0';
printf("\n post exp=%s",pe);
getch();
}
Q15.
Ans.
Write algorithm for Postfix Evaluation.
Following algorithm uses a stack to calculate postfix expression. Suppose P is an
arithmetic expression written in postfix notation. The following algorithm, which uses
a STACK to hold operands, evaluates P. This algorithm finds the VALUE of an
arithmetic expression P written in postfix notation.
1. Add a right parenthesis ‘)’ at the end of P.
2. Scan P from left to right and repeat steps 3 & 4 for each element P until the
‘)’ is encountered.
3. If an operand is encountered, then:
Push it into STACK
4. If an operator Ø is encountered, then:
a. Remove the two top elements of STACK, where A is the top element
and B is next-to top element.
b. Evaluate B Ø A
c. Place the result of (b) back on STACK
5. Set VALUE equal to the top element of STACK
6. Exit.
Q16.
Ans.
Write a program to find result of an infix expression.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char ie[20];
char pe[20];
char s[20];
char *p,c;
int p1,p2;
int i,t=0,k=0,j=0,si[20];
clrscr();
scanf("%s",&ie);
printf("infix=%s",ie);
i=strlen(ie);
ie[i]=NULL;
i=0;
while(ie[i]!=NULL)
{
if(ie[i]=='+'||ie[i]=='-'||ie[i]=='*'||ie[i]=='/')
{
if(t==0)
{
SUBJECT: DATA STRUCTURE
32/63
s[t]=ie[i];
t++;
}
else
{
if(ie[i]=='*'||ie[i]=='/')
{
s[t]=ie[i];
t++;
}
else
{
while(s[t-1]=='*'||s[t-1]=='/'||s[t-1]=='-'||s[t-1]=='+')
{
pe[k]=s[t-1];
k++;
t--;
}
s[t]=ie[i];
t++;
}}}
else
{
pe[k]=ie[i];
k++;
}
i++;
}
t--;
while(t!=-1)
{
pe[k++]=s[t--];
}
pe[k]='\0';
printf("\npostfix=%s",pe);
i=strlen(pe);
j=0;
t=-1;
while(j<i)
{
if(pe[j]=='+'||pe[j]=='-'||pe[j]=='/'||pe[j]=='*')
{
p1=si[t--];
p2=si[t];
switch(pe[j])
{
case '+':
si[t]=p2+p1;
break;
case '-':
si[t]=p2-p1;
break;
case '*':
SUBJECT: DATA STRUCTURE
33/63
si[t]=p2*p1;
break;
case '/':
si[t]=p2/p1;
break;
}
}
else
{
t++;
c=pe[j];
p=&c;
si[t]=atoi(p);
}
j++;
}
printf("\nans=%d",si[0]);
getch();
}
Q17.
Ans.
Write a program of priority queue.
#include<stdio.h>
#include<conio.h>
void main()
{
int pq[10],n=0,i,c,e;
clrscr();
do
{
printf("\nenter 1 to insert 2 to delete 3
for print 4 for exit");
scanf("%d",&c);
if(c==1)
{
if(n==10)
printf("overflow");
else
{
if(n==0)
{
printf("\nenter ele");
scanf("%d",&pq[n]);
n=n+1;
}
else
{
i=n;
printf("\nenter ele");
scanf("%d",&e);
while(pq[i-1]>e&&i>0)
{
pq[i]=pq[i-1];
i--;
}
pq[i]=e;
n=n+1;
}
}
}
if(c==2)
{
if(n==0)
printf("\nunderflow");
else
{
printf("\ndeleted ele=%d",pq[0]);
i=0;
while(i<n-1)
{
pq[i]=pq[i+1];
i++;
}
n--;
}
}
if(c==3)
{
for(i=0;i<n;i++)
printf("%d ",pq[i]);
}
}while(c!=4);
}
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
Q18.
Ans
Write a program of De-queue.
#include<stdio.h>
#include<conio.h>
void main()
{
int q[50],r=-1,f=-1,i,c;
clrscr();
do
{
printf("\n Enter 1 for insert from rear 2 for insert from front");
printf("\n Enter 3 to delete from rear 4 to delete from front ");
printf("\n Enter 5 to print 6 for exit :-> ");
scanf("%d",&c);
if(c==1)
{
if(r==4)
printf("overflow");
else
{
if(f==-1)
f=r=0;
else
r++;
scanf("%d",&q[r]);
}
}
if(c==2)
{
if(f==0)
printf("overflow");
else
{
if(f==-1)
f=r=0;
else
f--;
scanf("%d",&q[f]);
}
}
if(c==3)
{
if(r==-1)
printf("under flow");
else if(r==f)
f=r=-1;
else
r=r-1;
}
if(c==4)
{
if(f==-1)
printf("under flow");
else if(r==f)
34/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
35/63
f=r=-1;
else
f++;
}
if(c==5)
{
for(i=f;i<=r;i++)
printf(" %d",q[i]);
}
}while(c!=6);
}
Q 19. How can you implement recursive procedures using stacks? Explain.
Ans. Recursion is implemented using stacks.
Recursion is the process in which a function calls itself directly or indirectly.
Whenever a function calls itself, its call is placed on the stack. When all the calls are
placed on the stack, the stack unwinds and all the calls are executed. In this way, a
stack is used in recursion.
The chain of events is:

Each call of a procedure or a function causes an activation record be be pushed
on to a run time stack

An activation record represent parameters, local data, and some bookkeeping
information

A chain of n recursive calls causes n structurally identical activation records to be
pushed on the run time stack

Upon termination of a procedure the run time stack is popped, and the context
around the call is reestablished

For recursive calls, the state of the previous activation of the recursive procedure
is reestablished
Q 20. Using Quick Sort, sort the following data:
44, 33, 11, 55, 77, 90, 40, 60, 99, 22, 88, 66
Ans.
The steps in sorting the elements are:
A is the list of 12 elements
44, 33, 11, 55, 77, 90, 40, 60, 99, 22, 88, 66
Beginning with the last number 66, scan the list from left to right, comparing each
number with 44 and stopping at the first number less than 44. The number is 22.
Interchange 44 and 22.
22, 33, 11, 55, 77, 90, 40, 60, 99, 44, 88, 66
Beginning with 22, scan the list from left to right, comparing each number with 44 and
stopping where number is greater than 44. The number is 55. Interchange 44 and 55
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
36/63
22, 33, 11, 44, 77, 90, 40, 60, 99, 55, 88, 66
Now beginning with 55, scan the list in original direction, from right to left. Stop when
a number is less than 44. It is 40. Interchange 44 and 40.
22, 33, 11, 40, 77, 90, 44, 60, 99, 55, 88, 66
Beginning with 40, scan from left to right. First number greater than 44 is 77.
Interchange them
22, 33, 11, 40, 44, 90, 77, 60, 99, 55, 88, 66
Beginning with 77, scan from right to left. We don’t meet any number less than 44.
This means all numbers have been sorted according to 44.
Thus 44 is correctly placed in its final position.
Now we must continue for the other elements.
Q 21. Write the complexity of various sorting algorithms.
Ans.
Name
Bubble sort
Selection sort
Insertion sort
Binary tree sort
Merge sort
Quick sort
Best
Average
O(n)
O(n2)
O(n)
O(n log n)
O(n log n)
O(n log n)
—
O(n2)
O(n + d)
O(n log n)
O(n log n)
O(n log n)
Worst
2
O(n )
O(n2)
O(n2)
O(n2)
O(n log n)
O(n2)
Memory Method
O(1)
O(1)
O(1)
O(n)
O(n)
O(log n)
Exchanging
Selection
Insertion
Insertion
Merging
Partitioning
Q 22. Write steps to insert an element ITEM at location LOC in array A[]
Ans.
INSERT
A is linear array with N elements. K is the position where ITEM is to be inserted
1. Set I=N
2. Repeat while I>=K
a) Set LA[I+1]=A[I]
b) Set I=I-1
3. Set A[K]=ITEM
4. Set N=N+!
5. Exit
Q 23. What are the conditions for overflow and underflow for a circular queues?
Ans.
Underflow Operation
This algorithm is called before deleting an element and return true if circular queue is
empty else return false
Underflow
1.if rear = = -1 and front==-1
2.then return true
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
37/63
3.else retun false
4 exit
Overflow Operation
This algorithm is called before inserting an element to check whether a
circular queue is full or not. This algorithm will return true if queue is full else return
false.
Overflow
1 If rear ==front-1
2 then return true
3 else return false
4 exit
Q 24. Write procedure to insert an element in a circular queue
Ans.
void addq(int *arr, int item, int *pfront, int *prear)
{
if((*prear==MAX-1&&*pfront==0)||(*prear+1==*pfront))
{
printf("Overflow");
exit();
}
if(*prear==MAX-1)
*prear=0;
else
(*prear)++;
arr[*prear]=item;
if(*pfront==-1)
*pfront=0;
}
Q 25. Write a procedure to insert a node in doubly linked list.
Ans.
void add(struct node **s, int num)
{
struct node *q;
q=(struct node*)malloc(sizeof(struct node));
q->prev=NULL;
q->data=num;
q->next=*s;
(*s)->prev=q;
*s=q;
}
Q 26. Write algorithm to reverse a string using stacks
Ans.
REVERSE( STACK is the stack used in reversal, and Expression is the reverse
string)
1. If String is empty
a) Write UNDERFOW
b) Return
2. While not end of string, repeat
a) Push in STACK, each character one by one
3. While stack not empty, repeat
a) Pop characters from STACK and add to Expression
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
38/63
4. Exit
Q 27. Write steps to insert an element in a dequeue
Ans.
In a deque, elements can be inserted at both ends
Insertion from rear:
Insertrear
1. If rear==max
a) Write “overflow”
b) Exit.
2. rear = rear+ 1
3. Q [rear] = item
4. Exit
Insertion from front
Insertfront
1. If front==-1
a) Write “overflow”
b) Exit
2. front = front+1
3. Q[front]=item
4. Exit
Section – C
[QUESTIONS 1 TO 30]
2 Marks Questions
Q1.
What is big O notation?
Ans. The big O notation provides a theoretical measure of the time or memory required by
an algorithm. It also enables the user to compare the expected run times. It
calculates the order of the equation required to maintain the complexity of the
algorithm.
Q2.
What are the various data qualifiers?
Ans. Qualifiers are used in association with data types. Qualifiers allow you to add
meaning to the data type. Data type qualifiers affect the allocation or access of data
storage. Various programming languages support various qualifiers. Some of the
qualifiers are discussed below.
Long, signed, unsigned, const, volatile, restrict.
Q3.
Ans.
Write function in “C” language to create a tree.
void create(char n)
{
btree=(struc node*)malloc(sizeof(struct node));
btree->info=n;
btree->left=NULL;
btree->right=NULL;
}
Q4.
What does VSAM stands for.
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
39/63
Ans.
VSAM is abbreviation for Virtual Storage Access Method, a file management system
used on IBM mainframe.
Q5.
Ans.
What is a tree?
A graph with no cycles is called a tree. “Tree” is one of the most important nonlinear
data structures in computer algorithms. A tree structure depicts a hierarchical
relationship among the nodes of the tree “Parent-child” relationship is a typical
hierarchical relationship. In a tree, every child has got exactly one parent node, and
there are no loops
Q6.
Ans.
Give two applications of binary tree.
User interface: The best example for this are file system organization and windows
graphical interface.
Database System: Balanced search trees are good in situation that require both
sequential efficiency and random access while performing insertion and deletion.
Q7.
Ans.
Define AVL tree.
A binary search tree in which the difference of heights of the right and left sub-trees
of any node is less than or equal to one is known as AVL tree. The name is derived
from the names of inventors who are Adelson-Velskii and Land.
Q8.
What is a binary tree?
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
40/63
Ans.
Binary tree is an important class of tree data structure in
which a node can have at most two children (which are
sub-trees). Moreover, children (or the sub-trees) of the
node of a binary tree are ordered. One child is called the
“left” child and the other is called the “right” child
Q9.
Ans.
What is binary search tree?
A binary tree in which all elements in the left subtree of a node are less than the
contents of root & all elements in the right subtree are greater than or equal to the
contents of the root. Such a tree is called a binary search tree.
Q10.
Ans.
What are the applications of binary trees?
A binary tree is a useful data structure when two- way decisions must be made at
each point in a process. eg. Suppose that we want to find all duplicates in a list of
numbers. The no. of comparisons may be reduced by placing the first number in the
root. Each successive node is compared to the root, if it matches, we have a
duplicate of a number is lesser, we examine the left subtree, else if it is larger, we
examine the right subtree. Searching is also very easy in a binary tree.
Q11.
Ans.
What is the level & height of a binary tree?
Level:
The level of any node is equal to
length of its path from root to the
node: The root of any tree has
level equal to zero.
Height/Depth:
It is equal to one + maximum
level in a tree.
Level-0
Level-1
Level-2
Level-3
Q12.
Ans.
How a tree is represented in memory using linked organization?
A tree is implemented using nodes, a node consists of information part and two
address fields, one to store the address of left node and right to store the address of
right node. If a node does not have left or right child then a sentinel value known as
NULL value is inserted.
Q13.
Ans.
How a tree is represented in memory using sequential organization?
Under this technique an array is used. Root of the tree is stored at 1 st index of the
array. Left child is stored at double the index of parent node and right child is stored
at double the index of parent +1.
Q14.
Ans.
What is a heap tree?
In a heap tree root node is larger than its left and right node. Therefore in a heap tree
root node is the largest. It is immaterial in a heap tree whether left child is smaller
than right child or not. A heap tree has utility to perform heap sort which has
complexity as O(log2n).
Q15.
Ans.
What is a spanning tree?
A graph with no cycles is called a tree. A cycle is formed in a graph id both the start
vertex and the end vertex is the same. In other words, the path has the same first
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
41/63
and the last nodes. A spanning tree of a graph is a sub graph that contains all the
nodes without any cycles. It contains enough edges to form a tree. Various kinds of
spanning tree are available. The most important is the minimum spanning tree.
Q16.
Ans.
What does hashing mean?
Hashing involves computing the address of a data item by calculating a function on
the search key value. Hashing provides another method of retrieving data. Spell
checkers available in modern day word processors use it.
Q17.
Ans.
What is a strictly Binary tree?
Strictly binary tree are the binary tree whose each node contains zero or two child
nodes. A strictly binary tree with N leaf nodes contains 2N-1 child nodes.
Q18.
Ans.
What is complete binary tree?
Complete binary tree are strictly binary tree in which all leaf nodes are at the same
depth except last level. A complete binary tree with M nodes at level L can contain
2M nodes at level L+1.Therefore a complete binary tree of depth D contains
2D -1nodes.
Q19.
Ans.
Design Node of a Binary Search tree.
struct node
{
struct node *left’
int info;
struct node *right;
};
Q20.
Ans.
Write different types of traversing in binary tree.
Traversing (visiting all the nodes) a tree starting at node is often done in one of three
orders
 Preorder –
1. Process node,
2. Traverse left subtree in preorder
3. Traverse right subtree in preorder.
 Inorder –
1. Traverse left subtree in inorder
2. Process node
3. Traverse right subtree in inorder.
 Postorder –
1. Traverse left subtree in postorder
2. Traverse right subtree in postorder
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
42/63
3. Process node
Q21.
Ans.
Define Expression Tree.
Normal infix notation: (7-5) * (3+(1-2))
Tree equivalent:
*
/ \
/
\
+
/ \
/ \
7 5 3
/ \
1
2
Q22.
Ans.
Define searching.
Searching is the process of finding data from a set of given data items.
Types: Linear search(when the list is not sorted)
 Binary search(when the list is sorted)
Q23.
Ans.
Define Sorting.
Sorting is the process of arranging both numeric and alpha numeric data in a specific
order such as ascending or descending. Types: Selection sort
 Bubble sort
 Insertion sort
 Quick sort
 Merge sort
 Radix sort
 Heap sort
Q24.
Ans.
What are the various operations performed on binary search tree .
Q25.
Ans.
Design node of binary search tree.
Q26.
Ans.
Write function in “C” language to traverse a tree in Inorder.
void Inorder (bNode *T)
{
if (T !=NULL)
{
Inorder (T->left);
Basic operations are:
Insertion

Searching

Deletion

Traversal
struct node
{
into info;
struct node *left;
struct node *right;
};
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
43/63
printf (“%d” , T->data);
Inorder (T->right):
}
}
Q27. What are the conditions under which linear search and binary search techniques
are applicable?
Ans. For binary search, the array, must be sorted. Binary search works only on sorted
arrays. So, we must sort the array before applying the binary search technique on it.
Linear search does not require this condition.
Q 28
Ans.
29.
Ans.
What is dynamic memory allocation?
Dynamic memory allocation means to allocate memory at run time.
Mainly three functions are used for dynamic memory allocation.
1. Malloc
2. Calloc
3. Free
malloc and calloc are used to allocate memory at run time, and free is used to deallocate memory at run time.
What are various parameters to measure the efficiency
of an algorithm?
Two parameters to measure the efficiency of an algorithm are:
1. Speed
2. Memory requirements
These are also called time and space complexity measures.
Q 30. Comment on the statement “Sorting is required for an efficient searching”.
Ans. Sorting is required for an efficient searching. With an unsorted array, we can do
linear search, which is not a very efficient way of searching. Whereas, on sorted
array, we can do binary search, which is very efficient.
Section – C
[QUESTIONS 1 TO 39]
Q1.
Ans.
Q2.
Ans.
5 Marks Questions
Explain Binary search tree.
Binary search trees form an important
sub-class of binary trees. In an ordinary
tree, the elements are not ordered in any
way. A binary search tree is a binary
tree which is either empty or in which the
following criteria are satisfied.
1.
The left child node is smaller than
the root node.
2.
The right child node is greater than
or equal to the root node
3.
The left and right sub-trees of a
binary search tree are binary
search trees once again. As
Shown in fig:What is a Extended binary tree?
In an extended binary tree, the special nodes are added to a binary tree to
make it complete binary tree . In extended binary tree each node must contain
two child.
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
44/63
For example, let T be the following tree.
The extended binary tree of T is
Q3.
Ans.
1.
2.
3.
4.
5.
Write an algorithm for linear search.
Algorithm LINEAR (DATA, N, ITEM, LDC)
Hire DATA is a linear array with N elements & ITEM is a given item of information.
This algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search
is unsuccessful.
Linear
Set loc:=1
Repeat while data[loc]!=item
a. loc=loc+1
print loc
if loc=n+1
a) set loc:=0
exit
Q4.
Write PREORDER algorithms for Tree traversals.
Ans. Algorithm PREORDER (T): Given a binary tree whose root node address is given by
a pointer variable PTR, this algorithm traverse the tree in preorder in a recursive
manner.
Preorder –
1. Process node,
2. Traverse left subtree in preorder
3. Traverse right subtree in preorder.
Q5.
Ans.
Write INORDER algorithms for Tree traversals.
Algorithm INORDER (T): Given a binary tree whose root node address is given by a
pointer variable T, this algorithm traverse the tree in preorder in a recursive manner.
Inorder –
1. Traverse left subtree in inorder
2. Process node
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
45/63
3. Traverse right subtree in inorder.
Q6.
Ans.
Write POSTORDER algorithms for Tree traversals.
Algorithm POSTORDER (T): Given a binary tree whose root node address is given
by a pointer variable PTR, this algorithm traverse the tree in preorder in a recursive
manner.
Postorder –
1. Traverse left subtree in postorder
2. Traverse right subtree in postorder
3. Process node
Q7.
Ans.
List some of Hashing methods.
1. Division method: Choose a number m larger key in k. the hash function h is
defined by
H(k)=k(mod m) or H(k)=k(mod m)+1
Here k(mod m) denotes the remainder where k is divided by m. the second formula
is used where we want the hash address to range from 1 to m rather than from 0 to
m-1.
2. Mid square method: The key k is squared. Then the hash function h is defined by
H(k) =l
Where l is obtained by deleting digits from both ends of k 2.
3. Folding Method: The key k is partitioned into a number of parts k1,k2,………..,kr,
where each part except possibly the last has the same number of digits as the
required address. There the parts are added together, ignoring the last carry. That is
H(k) =k1+k2+k3+…….+kr
Where the leading digit carries, if any are ignored.
Q8.
Ans.
Define String and operations performed on strings.
Character type array is called string. String is a collection of characters. There are
several operations, which typically arise in the context of string manipulation Few
important such operations are outlined below
String Operations
IsEmpty (string s)
This operation checks whether a string “s” is null or not
StringLength (string s)
This operation computes the length of a string “s” .
String StringConcatenate (string s1, string s2)
This operation concatenates two strings “s” and “s2” to produce another string.
StringCopy (string s1, string s2)
This operation copies a string “s2” to “s1”. This operation becomes useful whenever
one strings to be assigned to another string.
StringCompare (string s1, string s2)
This operation compares two strings “s1” and “s2” and finds out whether they are
identical.
StringSearch (string s1,string s2)
This operation tests whether a given string “s2” occurs in another given string “s1”.
Q9.
Ans.
Explain Binary Search method.
When the given array is sorted then a better method of searching is possible. “k” is
the item to be searched. “A” is the sorted array. This method, known as binary
search, makes a comparison between “k” and the middle element of the array. Since
the array is sorted, this comparison results either in a match between “k” and the
middle element of “A”, or identifying the left half or the right half of the array to which
the desired element may belong. In the case when the current element is not equal to
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
46/63
the middle element of “A” , the procedure is repeated on the half in which the desired
element is likely to be present. Proceeding in this way, either the element is detected
or the final division leads to half consisting of no element. In this case, it is
ascertained that the array does not contain “k”. This is a very efficient method of
searching because each comparison enables one to eliminate half of the elements
form further consideration. Because of this basic principle of elimination, the method
is also known as dichotomous search.
Q10.
Ans.
Explain the time complexity of the average case for the bubble sort.
The bubble sort algorithm has two loops: inner and outer. The outer loop i.e. must
iterate as many times as the elements in the array while the inner loop iterates n
times for the first time, n-1 times second time and go on decreasing. The total
number of comparisons made are (n+1)+(n-2)+…+2+1=n(n-1)/2 or O(n2).
The average case for the bubble sort is also n2.
Q11.
Ans.
List different searching techniques and explain one in detail.
Searching is the process of finding data from a set of given data items.
 Linear Search
 Binary Search
 Search trees
 Hash table methods
Linear Search: The linear search is straightforward method of retrieving elements.
This is often considered the simplest technique for searching an unordered list of
elements. In linear search, the list is scanned element by element for the element to
be retrieved. When an appropriate match is found, a message is displayed. A
sequential search can be applied to any kind of list static or dynamic. Following are
some of the properties of the linear search technique.
 The item to be found is called the key.
 The search function will return the index number (for a static list) or a pointer (for
dynamic list) when item is found in the list.
 If the key cannot be found in the list, then not found value is returned eg. –1 for a
static list or NULL for a dynamic list.
Q12.
Ans.
Write down the binary search algorithm.
Let A be an array of N elements and ele is the element to be searched in the array.
Step 1. Start=0, End=N-1, Loc=-1
Step 2. Repeat Steps 3, 4 while Start<=End and Loc=-1
Step 3. Mid=(Start+End)/2
Step 4. if A[Mid]=ele then
i. loc=mid
ii. exit
else
if A[Mid]<ele then
start=Mid+1
else
end=mid-1
[end of If]
[end of while]
Step 5. Exit
Q13.
Ans.
Write an algorithm to search an element from a binary search tree.
Variables to be used:
1.INFO
is the information field of node.
2.LEFT
points to left child
3.RIGHT
Points to right child
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
47/63
4.PAR
points to parent node
5.LOC
points to ITEM if exists otherwise points to NULL
6.ITEM
which is to search
7.ROOT
is the root of tree
8.PTR
points to current node
Algorithm:
1. If ROOT=NULL, then LOC:=NULL and PAR:=NULL
2. If ITEM=INFO[ROOT] then set LOC:=ROOT and PAR:=NULL and Return
3. If ITEM<INFO[ROOT], then
Set PTR:=LEFT[ROOT] and SAVE:=ROOT
Else:
Set PTR:=RIGHT[ROOT] and SAVE:=ROOT
4.Repeat steps 5 and 6 while PTRNULL:
5.If ITEM=INFO[PTR],
then: set LOC:=PTR and PAR:=SAVE and return
6.If ITEM<INFO[PTR], then:
set SAVE:=PTR and PTR:=LEFT[PTR]
else
set SAVE:=PTR and PTR:=RIGHT[PTR]
7.set LOC:=NULL and PAR:=SAVE.
8.Exit
Q14.
Ans.
Write an algorithm to insert an item into a heap tree.
Variables to be used:
1.PAR
points to parent node
2.ITEM
which is to search
3.ROOT
is the root of tree
4.CHILD
is the child to delete
N
represents total number of nodes.
Algorithm:
1.
set N:=N+1 and PTR:=N
2.
Repeat step 3 to 6 while PTR<1
3.
set PAR:=PTR/2
4.
If ITEM<=TREE[PAR] then
Set TREE[PTR]:=ITEM, and return
5.
set TREE[PTR]:=TREE[PAR]
6.
set PTR:=PAR
7.
set TREE[1]:=ITEM
8.
Return
Q15.
Ans.
Discuss complexity of heap sort.
Complexity of heap sort can be calculated in following two phases:
a) If H is a heap tree. The number of comparisons to find the appropriate
place of a new element ITEM in H cannot exceed the depth of H. Since H
is a complete tree, therefore its depth is bounded by log2m where m is
total number of elements in H.
b) If there are m elements in heap tree then there is need to place m
elements and each element requires log2m comparisons. Therefore
complexity is O(nlog2n).
Q16.
Ans.
Write an algorithm for Bubble sort .
Algorithm BUBBLE (DATA, N)
Here DATA is an array with n elements. This algorithm sorts the elements in DATA.
1.
Repeat steps 2 & 3 for k = I to N-I
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
2.
3.
4.
48/63
Set PTR: = 1 [Initializes pass pointer]
Repeat while PTR ≤ N-K [Execute pass]
a) If DATA [PTR] > DATA [PTR +1], then interchange DATA [PTR] & DATA
[PTR+1]
[End of If structure]
b) Set PTR: = PTR+1
[End of inner loop]
[End of step 1 outer loop]
Exit
Q17.
Ans.
Write an algorithm for linear search.
Algorithm LINEAR (DATA, N, ITEM, LoC)
Hire DATA is a linear array with N elements & ITEM is a given item of information.
This algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search
is unsuccessful.
1.
[Insert ITEM at the end of DATA]
Set DATA [N+1]: = ITEM
2.
[Initialize counter]. Set LOC: =1
3.
Search for ITEM]
Repeat while DATA [LOC]  ITEM
Set LOC: LOC +1
[End of roop]
4.
[Successful?] If LOC= N+1, then Set LOC: = 0
5.
Exit.
Q18.
Ans.
Write an algorithm for merge sort.
Algorithm Merge (Arr, LBound, UBound, MID value)
1.
A=UBound
2.
B=MIDvalue+1
3.
C=LBound
4.
Repeat while (A<MIDvalue) and (B<=UBound)
If (Arr[A] < Arr [B])
Then L [C]= Arr [A]
C= C+1
A=A+1
Else
Arr2 [C] = Arr [H]
B = B+1
C = C+1
5.
Repeat while (IL = MIDvalue)
Arr2[C] = Arr[A]
A = A+1
C = C+1
6.
Repeat while (J L = Ubound)
Arr2 [C] = Arr[C]
B = B+1
C = C+1
7.
Repeat for A = LBound, LBound + -------UBound
Arr [A] = Arr2[A]
8.
Exit
Q19. Write a program for quick sort.
Ans.
#include<stdio.h>
Q20. Write a program for Merge Sort.
Ans.
#include<stdio.h>
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
#include<conio.h>
#define max 10
int partition();
void quick();
void p();
int a[max],low,high;
void main()
{
int i;
low=1;
high=max;
for(i=1;i<=max;i++)
{
printf("\nEnter the number: ");
scanf(“%d”,&a[i]);
}
quick();
getch();
}
void quick(int a[],int low,int high)
{
int j,i;
if(low < high)
{
j=partition();
p();
}}
int partition()
{
int key,i,j,temp;
char over='f';
key=a[low];
i=low+1;
j=high;
while(!over)
{
while(key > a[i])
{ i++; }
while(key < a[j])
{
j--;
}
if(i < j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
over='t';
}
}
temp=a[low];
a[low]=a[j];
#include<conio.h>
#define max 10
int a[max];
void simple();
void proc();
void main()
{
int low=0,high,i,mid;
high=max-1;
for(i=0;i<max;i++)
{
printf("\nEnter the number: ");
Scanf(“%d”,&a[i]);
}
proc();
for(i=0;i<max;i++)
{
printf(“%d”,a[i]);
}
getch();
}
void proc(int a[],int low,int high)
{
int mid;
if(low < high)
{ mid=(low + high)/2; }
proc();
proc();
simple(a, low, high,mid);
}
void simple(int a[],int i,int j,int high)
{
int k,m,n,temp[max];
while((i <= j-1) && (j <= high))
{
if(a[i] < a[j])
{
temp[k]=a[i];
i++;
k++;
}
else
{
temp[k]=a[j];
j++;
k++;
}
if(i <= j-1)
{
for(m=0;m<=j-1;m++)
{ temp[k]=a[m];
k++;
}}
else
{
49/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
a[j]=temp;
printf(“%d\n”,a[low]);
return j;
}
void p()
{int j;
quick(a,low,j-1);
quick(a,j+1,high);
}
Q21.
Ans.
Write a program of selection sort.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,t;
clrscr();
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<9;i++)
for(j=i+1;j<10;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
for(i=0;i<10;i++)
printf(" %d",a[i]);
getch();}
Q23.
Ans.
Write a program of insertion sort.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,t;
clrscr();
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=1;i<=9;i++)
{
j=i-1;
t=a[i];
while(t<a[j])
{
a[j+1]=a[j];
j--;
if(j==-1)
{
a[j+1]=t;
break;
50/63
for(m=j;m<=high;m++)
{ temp[k]=a[m];
k++;
}} }
for(m=i;m<=high;m++)
{
a[m]=temp[k];
k++;
}}
Q22.
Ans.
Write a program of bubble sort.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,t;
clrscr();
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=9;i>0;i--)
for(j=0;j<=i;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
for(i=0;i<10;i++)
printf(" %d",a[i]);
getch();
}
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
}}
a[j+1]=t;
}
for(i=0;i<10;i++)
printf(" %d",a[i]);
getch();
}
Q24.
Ans.
Write a program of Binary search.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[20],i,n,beg,end,mid=0,item;
clrscr();
printf("HOW MANY VALUES YOU WANT TO ENTER");
scanf("%d",&n);
printf("ENTER VALUES");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
beg=0;
end=n-1;
printf("ENTER ITEM");
scanf("%d",&item);
while(beg<=mid)
{
mid=(beg+end)/2;
if(a[mid]==item)
{
printf("VALUE IS FOUND AT LOCATION:%d",mid);
getch();
exit(0);
}
if(a[mid]>item)
{
end=mid;
}
else
{
beg=mid;
}
}
printf("VALUE NOT FOUND");
getch() ;
}
Q25. Write complexity of various sorting techniques.
Ans.
 Bubble: O(n2)

Insertion : O(n2)
51/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
Q26.
Ans.

Selection: O(n2)

Merge :O(n log(n))

Radix: o(k*n)

Heap: O(n log(n))

Quick: O(n2)
What are the various operations performed on binary search tree and design
node of binary search tree and write a c function to create a tree.
Basic operations are:
Insertion

Searching

Deletion

Traversal
struct node
{
char info;
struct node *left;
struct node *right;
};
void create(char n)
{
btree=(struc node*)malloc(sizeof(struct node));
btree->info=n;
btree->left=NULL;
btree->right=NULL;
}
Q27.
52/63
Write a function in “C” language to insert a element in a tree.
Ans. void insert(char n)
{
if(btree==NULL)
{
create(n);
return;
}
else
{
ptr=btree;
while(ptr!=NULL)
{
if(ptr->info==n)
{
printf(“node already exists”); return;
}
else
{
if(ptr->info<n)
{
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
ptr->right=(struc node*)malloc(sizeof(struct node));
ptr=ptr->right;
ptr->info=n;
ptr->right=NULL;
ptr->left=NULL;
return;
}
else
{
ptr=ptr->right;
continue;
}
}
else
{
if(ptr->info>n)
{
if(ptr->left==NULL)
{
ptr->left=(struc node*)malloc(sizeof(struct node));
ptr=ptr->left;
ptr->info=n;
ptr->right=NULL;
ptr->left=NULL;
return;
}
else
{
ptr=ptr->left;
continue;
}
}
}
}
}
Q28.
Write a function in “C” language to search a element in a tree.
Ans.
struct node* search(char n)
{
int f=0;
ptr=NULL;
while(ptr!=NULL)
{
if(ptr->info==n)
{
f=1;
break;
}
53/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
54/63
else
if(ptr->info>n)
{
ptr=ptr->left;
continue;
}
else
if(ptr->info<n)
{
ptr=ptr->right;
continue;
}
}
if(f==0)
{
printf(“node found”);
return (ptr);
}
else
{
printf(“node not found”);
return(NULL);
}
}
Q29.
Ans.
Explain Binary Tree Traversing.
Traversal of a binary tree is one of the most important operation required to be done
on a binary tree. Many other operations involving binary tree data structure often
need to traverse or walk through a given tree. Traversing is a process of visiting
every node in the tree exactly once.
Inorder Traversal
If a tree “T”, is traversed in an “inorder” fashion then the left sub-tree of “T” is
traversed first, then the root node of “T” is visited and then the right sub-tree of “T” is
traversed. The “C” function for inorder traversal of the tree, T, is presented below.
Void Inorder (bNode *T)
{
if (T !=NULL)
{
Inorder (T->left);
printf (“%d” , T->data);
Inorder (T->right):
}
}
Preorder Traversal
If a tree. “T” , is traversed in “preorder” fashion then the root node of “T” is visited
first and then the left sub-tree of “T” is traversed and finally the right sub-tree of “T” is
traversed. The “C” function for Preorder traversal of the tree, T, is presented below.
Void Preorder (bNode *T)
{
If (T!= NULL)
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
55/63
{
printf (“%d” , T->data);
Preorder (T->left);
Preorder (T->right);
}
}
Postorder Traversal
If a tree, “T” , is traversed in “postorder” manner, then the left sub-tree of “T” is
traversed first, then the right sub-tree of “T” is traversed and finally the root node of
“T” is visited . The “C” function for Postorder traversal of the tree, T, is presented
below.
void Postorder (bNode *T)
{
Postorder (T->left);
Postorder (T->right);
printf (“%d” , T->data);
}
}
Q.30. Explain malloc and calloc
Ans.
Malloc
malloc requires one argument - the number of bytes you want to allocate
dynamically.
If the memory allocation was successful, malloc will return a void pointer - you can
assign this to a pointer variable, which will store the address of the allocated
memory.
If memory allocation failed (for example, if you're out of memory), malloc will return a
NULL pointer.
Example:
int *ptr;
int number=2;
ptr = malloc(number*sizeof(int));
Calloc
calloc is similar to malloc, but the main difference is that the values stored in the
allocated memory space is zero by default. With malloc, the allocated memory could
have any value.
calloc requires two arguments. The first is the number of variables you'd like to
allocate memory for. The second is the size of each variable.
Like malloc, calloc will return a void pointer if the memory allocation was successful,
else it'll return a NULL pointer.
int *ptr;
ptr = calloc(3, sizeof(int));
Q 31. draw the binary tree corresponding to following tree traversals
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
Inorder: D B F E A G C L J H K
Postorder: D F E B G L J K H C A
Inorder
Postorder
56/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
Q 32. Construct a binary search tree with the following nodes:
14 45 16 22 12 65 43 33 18 30
57/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
58/63
Q 33. What are the steps to delete a node in BST? Explain with the help of an example.
Ans.
To delete a node from a binary search tree, there are four cases to consider:
a)
b)
c)
d)
No node in the tree containing the specified data.
The node containing the data has no children
The node containing the data has exactly one child
The node containing the data has two children.
Case a) Print the message: data not found
Case b) Memory occupied by the node is freed
Case c) Pointer to the parent of the node to be deleted points to the child of
the node to be deleted
Case d) The data of the inorder successor of the node to be deleted in its
location. Then the inorder successor is deleted.
For example, deleting a node with only one child
Before deletion:
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
After deletion
59/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
60/63
Q 34. Explain the concept of dynamic memory allocation and static memory allocation
with the help of an example.
Ans.
Dynamic memory allocation means to allocate and de allocate memory at run time.
It can be achieved using primarily three functions:
malloc, calloc and free.
Malloc
malloc requires one argument - the number of bytes you want to allocate
dynamically.
If the memory allocation was successful, malloc will return a void pointer - you can
assign this to a pointer variable, which will store the address of the allocated
memory.
If memory allocation failed (for example, if you're out of memory), malloc will return a
NULL pointer.
Example:
int *ptr;
int number=2;
ptr = malloc(number*sizeof(int));
Calloc
calloc is similar to malloc, but the main difference is that the values stored in the
allocated memory space is zero by default. With malloc, the allocated memory could
have any value.
calloc requires two arguments. The first is the number of variables you'd like to
allocate memory for. The second is the size of each variable.
Like malloc, calloc will return a void pointer if the memory allocation was successful,
else it'll return a NULL pointer.
int *ptr;
ptr = calloc(3, sizeof(int));
Static memory allocation means to allocate memory at compile time. It can be
achieved by using arrays. Memory allocated statically cant be changed later on
during program execution.
Q35.
Ans.
Discuss how stacks are used during tree traversal?
There are three ways to traverse trees.
Preorder
Inorder
Postorder
The algorithms for these three techniques are:

Preorder –
1. Process node,
2. Traverse left subtree in preorder
SUBJECT: DATA STRUCTURE (BSC/DCA-2)

61/63
3. Traverse right subtree in preorder.
Inorder –
1. Traverse left subtree in inorder
2. Process node
3. Traverse right subtree in inorder

Postorder –
1.Traverse left subtree in postorder
2.Traverse right subtree in postorder
3.Process node
All these algorithms use recursion. It is almost impossible to write traversal
algorithms without the use of recursion. And stacks are used in recursion, so trees
can’t be traversed without stacks.
Q 36. Define the following terms in context of binary trees.
Height, Path Length, Leaf Node, Root Node, Ancestor Node
Ans.
Height: The height or depth of a binary tree is the maximum level of the tree-1.
For example, in the above tree, the height/depth is 3
Path Length: The path length of a node is the number of nodes encountered on
spanning the tree back to the root. For example, the path length from node A to node
D is 3
Leaf node: A leaf node is a node which has no child nodes. For example, nodes D, E
and F are leaf nodes.
Root node: Root node is the first node of the tree, from which the whole tree is
spanned. The root is always at level 0
Ancestor node: An ancestor node is the parent, or parent of parent and so on, of a
node. For example, the ancestors of node E are: node C and node A
Q 37. What is the difference between binary search and linear search?
Ans.
Binary Search: In binary search, the data must be sorted, and the comparison starts
at the middle. If the item is smaller than the middle, then search is carried out in the
first half of the data. If the item is greater than the middle element, the search is
carried out in the second half of the data. At each level, we keep leaving half the
data, and calculate a new middle. This way of searching is highly efficient
Linear Search: In linear search, the data can be unsorted, and the comparison starts
at the beginning. The comparisons are made with each element one by one. Number
of comparisons is very large, making it an inefficient way of searching.
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
Q 38. Apply the insertion sort algorithm to sort the following elements
25, 17, 31, 13, 2
Ans.
62/63
SUBJECT: DATA STRUCTURE (BSC/DCA-2)
63/63
Q 39. How many comparisons are required in liner search and binary search to
search the number 45 in the following list:
11,23,25,29,31,35,38,41,45,50
Ans.
Using linear search :
In linear search, a one-to-one comparison is made, so 45 is first compared to 11,
then to 23, then to 25 and so on. So total 9 comparisons are made.
Using binary search :
In binary search, searching starts from middle, so in this case 45 is first compared
with 31.
35 being greater than 31, is searched in the second half. So now 45 is compared with
41. next it is compared with 45 and a match is found, so in this case only 3
comparisons are made