Professional Documents
Culture Documents
Subject: Data Structure' (Bsc-It - 2) : Section - A 1 Marks Questions (Questions 1 To 141) (PAGE 1 TO 14)
Subject: Data Structure' (Bsc-It - 2) : Section - A 1 Marks Questions (Questions 1 To 141) (PAGE 1 TO 14)
Note:
This question-bank contains three sections.
Section-A contains 1 mark Multiple Choice Objective type questions.
Section-B contains 5 marks subjective questions.
Section-A contains 10 marks subjective questions.
Q2. A stack is a data-structure in which elements are stored and retrieved by:
a. FIFO method b.LIFO method
c. FCFS method d. None of the above
Q5. A queue is a data-structure in which elements are stored and retrieved by:
a. FIFO method b.LIFO method
c. FCFS method d. None of the above
Q6. If an array with the name, A exists which of the following statements is incorrect:
a. A++ b. printf(“%d”,*(A+1))
c. printf(“%u”,A+1) d. All are correct
Q8. The unary operator used with pointer variable to indirectly access the contents of memory
location pointed to by the pointer is called
a. Address-of operator b. dot operator
c. indirection operator d. asterisk operator
Q15. To access elements of a structure through a pointer , the operator used is:
a. . b. ->
c. <- d. *
Q16. A structure having atleast one of its members of the same type as the structure itself:
a. reference structure b. nested structure
c. self-referential structure d. none of the above
Q20. If p1 and p2 are pointers of integer type and x is also an integer-type of variable, which of these
expressions is valid:
a. p1*x b. p2+x
c. p1+p2 d.p1*p2
Q21. A linked list can be represented using two ways which are:
a. single and double b. single and circular
c. static and dynamic d. any of the above
Q22. Dynamic memory allocation for a node in a linked list is done from:
a. RAM b. ROM
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 3 of 83
Q27. The situation in which the user tries to delete a node from an empty linked list is called:
a: empty b: free
c. overflow d. underflow
Q28. When a new node is inserted in between a linked list, which of these is true:
a: only the nodes appearing after b: only the nodes appearing before
the new node needs to be moved the new node needs to be moved
c: the nodes appearing before d: None of the above
and after the new node need
to be moved
Q29. The situation in which memory is not available for the allocation of a new node:
a: empty b: free
c. overflow d. underflow
Q30. A linear linked list in which the next field of the last node points back to the first node is termed
as:
a: single linked list b: double linked list
c: circular linked list d: reversed linked list
Q31. A new node can be dynamically inserted anytime in a linked list, for which the memory manager
maintains a special list known as
a: available list b: free-storage list
c: single linked list d: dynamic storage list
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 4 of 83
Q34. The pointer used to point to the element in the beginning of the stack is called:
a: start b: front
c: root d: top
Q38. When converting an infix expression to postfix using algorithm, when ‘(‘ is encountered, it is:
a: added to postfix string b: pushed and operators are popped from the stack
c: pushed onto the stack d: options a and c are performed
Q39. The data-structure in which both insertion and deletion take place from the beginning:
a: linked list b: queue
c: tree d: stack
Q40. The postfix expression: 5 6 2 + * 12 4 /- when evaluated gives the following result:
a: 37 b: -37
c: 40 d: 3
Q42. The validity of an expression containing nested parentheses could be checked using:
a: linked list b: queue
c: tree d: stack
Q44. The notation in which the operator occurs between the operands is called:
a: infix notation b: prefix notation
c: postfix notation d: post-operator notation
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 5 of 83
Q48. In a priority queue, the elements with the same priority are processed according to:
a: First come first served basis b: priority
c: last in first come basis d: no specific order
Q49. The deque in which insertion is done at one end and deletion from both ends:
a: input-restricted deque b: output-restricted deque
c: input-output restricted deque d: Any of the above
Q50. A circular array queue with space for 10 elements in which front =6 and rear=9, insertion of next
element will take place at position:
a: 0 b: 5
c: 7 d: insertion can not take place due to
overflow situation
Q51. A data-structure in which each element is assigned a priority and the elements are
added/removed according to that priority :
a: priority list b: priority queue
c: stack d: none of the above
Q52. A linear data-structure in which elements could be inserted/deleted at either end but not in the
middle:
a: queue b: stack
c: deque d: circular queue
Q53. In a circular queue with 10 elements, if front is at 9 and rear at 4, the deletion of an element will
make front point to which position:
a: 0 b: -1
c: 3 d: 5
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 6 of 83
Q57. The nodes belonging to the same parent are known as:
a: descendants b: external nodes
c: child nodes d: siblings
Q59. A binary tree in which all the leaf nodes of the tree are at the same level:
a: complete binary tree b: binary search tree
c: strictly binary tree d: none of the above
Q60. At any level x of a binary tree, the maximum number of nodes are:
a. 2x b: 2*x
c: 2+x d: none of the above
Q61. What is the root node for the algebraic expression : a*(b+c)-d, if it is represented in the form of a
tree:
a: - b: +
c: a d: *
A
B
C
D E
G
F
a: 3 b: 4
c: 5 d: 2
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 7 of 83
Q65. A binary tree in which the node-values are not repeated is called:
a: B-tree b: binary search tree
c. binary ordered tree d: B+ tree
Q66. A binary search tree in which the nodes have been inserted in the following
order:60,55,95,40,30,100,35, the node with the value 47 will be inserted to the:
a: right of node with value 40 b: right of node with value 55
c: right of node with value 35 d: left of node with value 30
Q67. In the following post-order traversal of a binary tree: E,C,K,A,H,B,G,D,F, the root node is:
a: E b: H
c: F d: D
Q73. A linear list of elements in which deletion can be done from one end and insertion can take
place at the other end is called:
a: queue b: stack
c: tree d: branch
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 8 of 83
Q76. The ‘C’ declaration: int b[100]; reserves ____ successive memory locations, each large enough
to contain a single integer:
a: 200 b: 10000
c: 10 d: 100
Q78. The operation of processing each element in the list is known as:
a: sorting b: merging
c: inserting d: traversal
Q80. The elements of an array are stored successively in memory cells because:
a: in this way the computer can calculate b: computer architecture allows
the address of other elements keeping arrays to be stored serially only
track of address of first element
c: both of the above d: none of the above
Q82. If you wanted to make sure that closing parentheses ‘)’ match the opening parentheses ‘(‘ in a
mathematical expression, which data-structure could help you?
a: hash table b: stack
c: queue d: tree
Q83. The estimated amount of time required in executing an algorithm is referred to as _____ of the
algorithm.
a: time complexity b: space complexity
c: time and space complexity d: none of the above
Q84. If all the data to be sorted does not fit entirely in main memory, the sorting technique used is:
a: internal sorting b: external sorting
c: merge sorting d: sorting can not be performed
Q86. A theoretical measure of algorithm execution, usually the time/ memory needed , given the
problem size n , is referred to as:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 9 of 83
Q88. The root node of a binary tree whose preorder traversal is: F,B,A,D,C,E,G, I, H is:
a: F b: H
c: C d: none of these
Q89. The post-order traversal of an arithmetic expression will result in the expression being
represented as:
a: postfix b: prefix
c: infix d: none of the above
Q91. Which of the following cases does not exist in complexity theory:
a: best case b: worst case
c: average case d: Null case
Q95. Which of the following data structures is not a linear data structure:
a: arrays b: linked lists
c: both of the above d: none of the above
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 10 of 83
Q98. The memory address of the fifth element of an array can be calculated by the formula:
a: Base(Array)+w(5-lower bound) where b: Base(Array[5])+(5-lower bound)
w is the size of each element of array
c: Base(Array[5])+(5-upper bound) d: none of the above
Q100. Which of the following is not the required condition for binary search algorithm:
a: the list must be sorted b: a direct access to middle element
is needed
c: a mechanism to delete/insert elements d: None of the above
in list
Q101. Which of the following data structures can’t store non-homogeneous data-elements:
a: Arrays b: Records
c: Pointers d: None
Q106. When representing any algebraic expression E which uses only binary operations in a 2-tree:
a: the variables in E will appear as external b: the operations in E will appear as
nodes and operations as internal nodes external nodes and variables as
internal nodes
c: the variables and operations in E will d: the variables and operations in E
appear only as internal nodes appear only as external nodes
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 11 of 83
Q108. The inorder traversal of tree will yield a sorted listing of elements of tree:
a: binary tree b: binary search tree
c: heaps d: none of the above
Q110.A ________ is a data-structure that organizes data similar to a line in the super-market, where the
first one in the line is the first to be out:
a: queue b: stacks
c: any of the two above c: none of these
Q111. Which of the following abstract data types is not used by integer abstract data type group?
a: short b: int
c: float d: long
Q113. The variables which can be accessed by all modules in a program, are known as:
a: local variables b: internal variables
c: external variables d: global variables
Q114. The post order traversal of a binary tree is :DEBFCA, find out the preorder traversal:
a: ABFCDE b: ADBFEC
c: ABDECF d: ABDCEF
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 12 of 83
Q118. A set of several trees that are not linked to each other in any way
a: Forest b: Graphs
c: B-trees d: none of these
Q119. All the non-leaf nodes except the root node in a multi-way search tree of order, n have atleast:
a: n-1 children b: n children
c: n/2 children d: n*2 children
Q124. A tree in which the value in every node is more than node-values in its left subtree and less than
node-values in its right subtree:
a: binary sorted tree b: B-tree
c: B+ tree d: AVL tree
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 13 of 83
Q130. To reduce disk-accesses while searching for a record, the tree used is:
a: binary sorted tree b: B-tree
c: general tree d: AVL tree
Q134. If there are more than one paths between two nodes, it is a:
a: tree b: graph
c: circular linked list d: none of the above
Q136. A binary tree with n internal nodes has a max. of external nodes equal to:
a: n-1 b: n+1
c: n d: n/2
Q140. The algorithm used in dynamic memory allocation with minimum time:
a: First fit b: Best fit
c: Worst fit d: Next fit
Q141. The algorithm used in dynamic memory allocation which results in minimum fragmentation:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 14 of 83
Answers
Section-B
5-mark questions
1. Explain the time and space complexity of an algorithm. What is Big-O notation?
Ans.: Time complexity is related to the performance requirements of an algorithm i.e.
the amount of time a program needs to run to completion. The time T(P) taken by a program, is the sum of
compile time and run-time. Compile time does not depend on instance characteristics. Hence, only the run-time
of a program is considered.
The time spent on arithmetic operations depends on the numbers being entered and therefore to derive an
exact formula is impossible. Hence, we take a count of the number of program-steps.
Space complexity is the amount of memory the program needs. It is expressed in form of a function f(n), where
n is the input size for a given instance of the problem being solved. The space needed by an algorithm is the
sum of the following components:
Fixed part- this is independent of the characteristics of input and output.
Variable part- this is dependent upon instance characteristics.
Space complexity of an algorithm S(p) can be written as c+ Sp where c is a constant. When analyzing space-
complexity, we concentrate solely on estimating Sp which depends upon instance characteristics.
For eg. Given the following algorithm:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 15 of 83
Algo Sum(a,n)
{ s=0;
For i=1 to n
{s=s+a[i];
}
return s;
}
Its time complexity= no. of program steps=2n+3 and space complexity >= n+3
Big-O notation or Asymptotic notation- 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.
The function f(n)= O(g(n)) if and only if there exist positive constants c and n 0 such that f(n)<=c*g(n) for all n,
n>=n0
For eg: 3n+2 = O(n) as 3n+2 <=4n for all n>=2
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 16 of 83
printf("%d ",c[k]);
getch();
}
3. What is a pointer? What are the operations that can be performed on a pointer? Also point out
the uses of a pointer.
Ans: Pointer is a variable which stores the address of another variable for eg. an
integer pointer stores the address of integer variable.
int *a, b;
a=&b;
This means a gets the address of b.
The pointer should be of the same type as the data-type of the variable whose address it is to store.
Uses of a pointer:
1. Pointers help in performing dynamic allocation/ de-allocation of memory-
blocks.
2. They allow the changed values of function arguments to be accessible in
the calling function.
3. They allow the passing of an array into a function as a function
argument.
4. Pointers provide efficiency.
5. The pointer notation is also used to access array-elements.
It is declared in the same way as other arrays are declared except an asterik(*)
is specified before the array name.
ptr
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 17 of 83
The subscript of an array of pointers starts with 0. So, in the above-mentioned example, as the array-size is 3
elements, the subscript ranges from 0 to 2.
The elements of an array of pointers can be initialized and accessed in the following way:
void main()
{
int *p[3],a=10,b=20,c=30,i;
ptr[0]=&a;
ptr[1]=&b;
ptr[2]=&c;
for(i=0;i<=2 ;i++)
printf(“%d ”,*ptr[i]);
getch();
}
The three elements of the array of pointers are initialized resp. with the addresses of a, b and c. Now, these
elements could be accessed using a loop. The output will be 10 20 30 as *ptr[0] gives the value of ‘a; which is
10, * ptr[1] gives the value of ‘b’ which is 20 and *ptr[2] gives the value of c which is ‘30’.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 18 of 83
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 19 of 83
}
7. Write a program to find the sum of elements below the main diagonal and the sum of elements
above the main diagonal of a matrix.
Ans: Program to find the sum of elements above and below the main diagonal is as follows:
#include<stdio.h>
#include<conio.h>
void main()
{int a[3][3],i, j, sa=0, sb=0;
clrscr();
printf("Enter array elements\n");
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
scanf("%d",&a[i][j]);
for(i=0;i<=2;i++)
{for(j=0;j<=2;j++)
printf("%d ",a[i][j]);
printf("\n");
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(j>i)
sa+=a[i][j];
else
if(j<i)
sb+=a[i][j];
}
}
printf("Sum of elements above the main diagonal=%d\n",sa);
printf("Sum of elements below the main diagonal=%d\n",sb);
getch();
}
8. What is meant by reversing a linked list.? Write the algorithm for reversing.
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.
This is done using 3 pointers: save, ptr and temp. Initially temp points to start and both ptr and save point to
NULL. While traversing the list, temp points to the current node,ptr points to the node previously pointed to by
temp and save points to the node previously pointed to by ptr. The links between the nodes are reversed by
making the next field of the node pointed to by ptr to point to the last node and save point to the second last
node of the list. Start is made to point to the node pointed to by ptr in order to make the last node as the first
node of the list.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 20 of 83
3. save=NULL
4. while(temp != NULL)
a. save=ptr
b. ptr=temp
c. temp=temp->next
d. ptr->next=save
5. start=ptr
6. Exit
9. Write a program for deletion from the end of a double linked list.
Ans: The program for deletion from the end of a double linked list is as follows:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
void main()
{
int num;
char ch='y';
clrscr();
start=NULL;
while(ch=='y')
{ printf("Enter number");
scanf("%d",&num);
fflush(stdin);
nw=malloc(sizeof(struct node));
nw->info=num;
nw->next=NULL;
nw->back=NULL;
if(start==NULL)
{ start=nw;
last=nw;
}
else
{ nw->next=start;
start->back=nw;
start=nw;
}
printf("Continue?");
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 21 of 83
ch=getchar();
fflush(stdin);
}
ptr=start;
while(ptr!=NULL)
{printf("%d ",ptr->info);
ptr=ptr->next;
}
getch();
printf("\n");
ptr=last;
while(ptr!=NULL)
{printf("\n");
ptr=ptr->back;
}
getch();
printf("Deleting....");
if(start==NULL)
{printf("List is empty ");
exit(0);
}
else if(start==last)
{free(start);
start=last=NULL;
}
else
{save=last->back;
save->next=NULL;
free(last);
last=save;
}
printf("\n");
printf(“Displaying…\n”);
ptr=start;
while(ptr!=NULL)
{printf("%d ",ptr->info);
ptr=ptr->next;
}
getch();
}
10. What is a structure? How is it different from an array?
Ans: When different types of elements have to be put in a single unit, a structure needs to be used. For eg. a
structure of student type can be defined as follows:
struct student{ int rno;
char name[30];
float marks;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 22 of 83
};
struct student s1;
Here student is the structure-tag and rno, name, marks are structure elements or
members. s1 is a struct student type of variable with the size of 36 bytes, comprising
of rno, name and marks in a sequential order. One structure variable can be
assigned to another structure variable of the same type using assignment operator.
An array is a variable which contains elements of the same data-type in continuous memory locations. For
eg. an array containing marks of float type for 5 students, would be defined as follows:
float marks[5];
Here, an array with the name marks gets created of 20 bytes, as each float element
takes 4 bytes. An array variable can not be assigned to another array variable using assignment operator.
This can be achieved by copying element by element onto the other array.
A structure can contain an array as its member. Also, an array of structures can be defined.
12. Write an algorithm for counting the number of nodes in a single linked list.
Ans: The algorithm for counting the number of nodes in a single linked list is as
follows:
count_node(start)
1. Set count =0
2. Set temp=start
3. while temp !=NULL
i. Set count=count +1
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 23 of 83
13. What is the difference between static and dynamic memory allocation. Explain.
Ans: Static memory allocation refers to memory allocation at compile-time. For example an array is allocated
memory at compile time. That is, the size of the array can not be changed at run-time.
Dynamic memory allocation means allocating memory at run time from the heap portion of RAM. At
run-time, depending upon the user’s requirement, memory can be allocated, resulting in a better utilization of
memory.
The functions generally used for this are:
malloc
malloc requires one argument - the number of bytes to be allocated dynamically.
If the memory allocation is successful, malloc returns a void pointer – this can be assigned to a pointer
variable, which will store the address of the allocated memory.
If memory allocation fails , malloc returns a NULL pointer.
Example:
int *ptr;
ptr = malloc(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 blocks to be allocated memory for. The second is the
size of each block.calloc is used to allocate multiple memory blocks.
Like malloc, calloc returns a void pointer if the memory allocation was successful, else it returns a NULL pointer.
int *ptr;
ptr = calloc(3, sizeof(int));
realloc
If the space allocated is not sufficient, reallocation of space is possible using this function
free
This function is used to de-allocate the memory block which is no longer needed.
Static memory allocation is faster than dynamic. But in static memory allocation,
memory may be wasted or there may be a shortage of memory. On the other
hand, incase of dynamic memory utilization, only as much memory is allocated
as is needed. Thus it results in better memory utilization.
Info Link
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 24 of 83
contains data
Contains address of next node
Double linked list:> in this list each node contains three parts
previous field:-contains address of the previous node.
Info field:-contains data
Next field:- contains address of the next field.
As it has two links, to the previous and to the next node, it is known as double-linked list.
prev info next
Circular:> A linear linked list in which the next field of the last node points back to the first node instead of
containing a null value is called circular linked list.
Header linked list:> In this type of linked list a special node called header node is always present at the
beginning of the linked list. This header node contains some general information about the linked list such as
the number of nodes in the list, whether list is sorted or not, etc.
Header node
check_validity(top,expr)
1. Set I=0
2. While(I< number of_symbols_in_expression)
a. If (expr[I]=’(‘ or expr[I]=’{‘ or expr[I]=’[‘)
i. Push expr[I] onto the stack
b. Else If (expr[I]=’)’ or expr[I]=’}’ or expr[I] =’]’)
i. if(top=NULL)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 25 of 83
b) infix to prefix
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 26 of 83
b: When operation b is performed, top becomes equal to 4 and Ahmedabad is pushed onto the top of the
stack:
Stack: Delhi, Kolkatta, Patiala, Chandigarh, Ahmedabad
c: When operation c is performed, top becomes equal to 3 as pop operation is executed and the top-most
element is popped out of the stack which is Ahmedabad:
Stack: Delhi, Kolkatta, Patiala, Chandigarh
d: When operation d is performed, top becomes equal to 4 and Chennai is pushed onto the top of
the stack:
Stack: Delhi, Kolkatta, Patiala, Chandigarh, Chennai
e: When operation e is performed, as top is already 4 (the upper-most subscript of the array-stack) , an
“Overflow” situation is reported as there is no space left in the array-stack to push an element. The stack
remains as such, with no change:
Stack: Delhi, Kolkatta, Patiala, Chandigarh, Chennai
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 27 of 83
f: When operation f is performed, top becomes equal to 3 and Chennai is popped from the stack:
Stack: Delhi, Kolkatta, Patiala, Chandigarh
Q21. Evaluate the following postfix expression using algorithm and show the contents of the stack
after the execution of each operation: 20,30,+,50,40,-,*
Ans: The algorithm for postfix expression evaluation is as follows:
a. Add a right parenthesis ‘)’ at the end of P.
b. Scan P from left to right and repeat steps 3 & 4 for each element P until the ‘)’ is encountered.
c. If an operand is encountered, then:
a. Push it into STACK
d. 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. Push the result of (b) back onto the STACK
e. Set VALUE equal to the top element of STACK
f. Exit
Now evaluating the given postfix expression:
. When 20 is encountered, since it is an operand , it is pushed onto the stack:
Stack: 20
When 30 is encountered, since it is an operand , it is also pushed onto the stack:
Stack:20,30
When + is encountered , since it is an operator, two elements are popped out of the stack: So, A
becomes=30 and B becomes= 20 Now, B+A is performed, making the result=50 which is pushed onto the stack.
Stack: 50
When 50 is encountered, since it is an operand , it is pushed onto the stack:
Stack:50,50
When 40 is encountered, since it is an operand , it is pushed onto the stack:
Stack:50,50,40
When - is encountered , since it is an operator, two elements are popped out of the stack: So, A
becomes=40 and B becomes= 50 Now, B-A is performed, making the result=10 which is pushed onto the stack.
Stack: 50,10
When * is encountered , since it is an operator, two elements are popped out of the stack: So, A becomes=10
and B becomes= 50 Now, B*A is performed, making the result=500 which is pushed onto the stack.
Stack: 500
As the end of the string is encountered, the topmost element is popped out of the
stack and Value becomes =500 which is the result.
Q22. What is a priority queue? Explain. Write the algorithm for insertion in a priority queue.
Ans: It is a data-structure in which each element is assigned a priority and the elements are added or removed
according to that priority. While implementing a priority queue, the following two rules are applied:
a) The element with the highest priority is processed before any element of lower priority.
b) The elements with the same priority are processed according to the order in which they are added to
the queue.
The algorithm for insertion into a priority queue:
qinsert(start)
1. Set temp=start, prev =start
2. Allocate memory to nptr
3. If nptr=NULL
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 28 of 83
a. Print “Overflow”
b. Exit
4. Read item, prno
5. Set nptr->info=item
6. Set nptr->prno =prno
7. Set nptr->next=NULL
8. If (start=NULL or start->prno > prno)
a. start =nptr
b. start->next=temp
9. else
a. while(temp!=NULL)
i. if(temp->prno > prno)
1. prev->next=nptr
2. nptr->next=temp
ii. else
1. Set prev=temp
2. temp=temp->next
b. if(temp=NULL)
i. Set prev->next=nptr
10. Exit
Q23. Differentiate between LIFO and FIFO data-structures. Explain with example.
Ans: FIFO data-structures are those which work on the First In First Out basis. That is the element which enters
at the very last is inserted at the end and the element which is the first is deleted first. Queues are FIFO linear
data-structures. They are used for a variety of purposes and implemented in the form of array or linked lists.
Queues can be of a number of types: for eg. normal queues, circular queues, priority queues. They can not be
used in recursion. To implement a queue two pointers are needed- front which points to the first element and
rear which points to the last element. Applications: a) to execute a process on the first-come-first served basis
b) to execute processes according to their priority.
LIFO data-structures are the ones which work on the principle of last in first out. The element which is entered
last is popped out first. In this case, both insertions and deletions take place from the beginning. Stacks are
LIFO type of data-structures. They are used in recursion. Like queues, stacks are also implemented in the form
of arrays or linked lists. To implement stacks a single pointer is used which is called top. Other applications of
stacks are: graph traversal, conversion from infix to postfix, evaluation of postfix expression, parentheses-
validity checker in an expression.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 29 of 83
Operating systems often maintain a queue of processes that are ready to execute or that are waiting for
a particular event to occur.
Computer systems must often provide a “holding area” for messages between two processes, two
programs, or even two systems. This holding area is usually called a “buffer” and is often implemented as a
queue.
Our software queues have counterparts in real world queues. We wait in queues to buy pizza, to enter movie
theaters, etc. Another important application of the queue data structure is to help us simulate and analyze such
real world queues.
Q25. What are the operations that can be performed on a queue and at what end?
Ans: Queue is also called First-In–First-Out data-structure(FIFO). It is a linear list in which insertions take place
at the end and deletions take place from the front. Two pointers are used viz. front and rear. Queues are
usually represented as linear arrays in memory. They can also be represented in the form of linked lists.
The operations that can be performed on queues are as follows:
i. Traversing- This refers to accessing all the elements of the queue one by one. The processing
starts from the front and ends at rear.
ii. Searching- It is the process of finding the location of a given data element in the queue. This also
starts from the front and ends at rear.
iii. Insertion- It means adding a new data element to the queue. Insertion can also take place according
to priority. If it is a normal queue, both front and rear are made to point to the first and only element in the
queue. However, when further elements are added into the queue, rear is made to point to the new element
whereas front remains unchanged. This is so because insertion in a queue is from the end.
iv. Deletion- It means removing any existing data element from the queue. As deletion in a queue takes
place from the front, the front pointer is made to point to the next element in the queue and rear remains
unchanged.
Q26. What is a circular queue? What are its advantages over a normal queue. Suppose a queue is
maintained by a circular array holding 10 elements. Find the number of elements in the queue if:
c) front=3,rear=7
d) front=9,rear=4
e) front =4,rear=5 and then two elements are deleted.
Ans: In a normal queue, in the array implementation, if rear index reaches the maximum size of the queue,
even if there is space available on the left of front index, elements can not be inserted, thus resulting in wastage
of space. To solve this problem, circular queues are used. Although, a circular queue can be implemented as a
linked list, generally array-representation is used.
In this queue, if the rear index reaches the maximum size of the array, it is set to 0 and elements are inserted
from this position. The overflow situation occurs when either (front=0 and rear=max. -1 ) or (rear+1=front).
While deleting elements, if front becomes=(max-1), it is reset to 0.
Finding the no. of elements in a circular array queue which can hold 10 elements:
1. No. of elements=As rear>front: rear-front+1 = 7-3+1=5
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 30 of 83
Ans: a: When operation a is performed , front remains 0 but rear becomes equal to 3 as insertion in queue is
from the end and Chandigarh is inserted.
Queue: Delhi, Kolkatta, Patiala, Chandigarh
b: When operation b is performed , front remains 0 but rear becomes equal to 4 as insertion in queue is from
the end and Ahmedabad is inserted.
Queue: Delhi, Kolkatta, Patiala, Chandigarh, Ahmedabad
c: When operation c is performed, front becomes equal to 1 as deletion is from the front in a queue and rear
remains the same. Delhi is removed.
Queue: Kolkatta, Patiala, Chandigarh, Ahmedabad
d: When operation d is performed , front remains 1 but rear already being equal to 4 (the last subscript)
becomes 0 and Chennai is inserted. i.e now front points to Kolkatta and Chennai is the last element.
Queue: --Chennai, Kolkatta, Patiala, Chandigarh, Ahmedabad ->
e: When operation e is performed, it reports an “Overflow” situation and no element can be inserted as (rear+1)
=front. The queue remains the same as before:
Queue: --Chennai, Kolkatta, Patiala, Chandigarh, Ahmedabad->
f: When operation f is performed, front becomes equal to 2 as deletion is from the front in a queue and rear
remains the same i.e. 0. Kolkatta being the first element in the queue, is removed.
Queue: --Chennai, Patiala, Chandigarh, Ahmedabad->
Q28. Define Underflow and Overflow states for an ordinary queue and circular queue.
Underflow state
This occurs when there are no elements in the queue.
Underflow
1.if front = = -1
2.then return true
3.else return false
4 exit
Overflow state
This part of the 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-1 [where max is the array-size]
2 then return true
3 else return false
4 exit
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 31 of 83
Underflow Condition
This algorithm is called before deleting an element and returns true if circular queue is empty else returns false
Underflow
1.if front==-1
2.then return true
3.else return false
4 exit
Overflow Condition
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 it will return false.
Overflow
1 If rear = front-1 or (front =0 and rear = max-1)
2 then return true
3 else return false
4 exit
Q29. 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 pushed onto a run-time stack
An activation record represents parameters, local data and some bookkeeping information
A chain of n recursive calls causes n structurally identical activation records to be pushed onto the run-time
stack
Upon termination of a procedure the run-time stack is popped, and the context around the call is re-
established
For recursive calls, the state of the previous activation of the recursive procedure is re-established
Q30. Write a recursive algorithm for insertion into a binary search tree.
Ans: A Binary Search Tree is a binary tree in which the value in each node is greater than the values of nodes
in its left subtree and less than the values of nodes in its right subtree.
The recursive algorithm for insertion into a binary search tree:
Insert_node(item,ptr)
1. if (! ptr)
i. Allocate memory for ptr
ii. Set ptr->info =item
iii. Set ptr->left = NULL
iv. Set ptr->right =NULL
2. Else
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 32 of 83
Q31. Write the algorithm for deletion of a node from a binary search tree.
Ans: The algorithm for deletion in a Binary Search Tree is as follows:
del_node(item, ptr)
1. If !(ptr)
a. Print “item does not exist” and goto step 3
2. If item< ptr->info
Call del_node(item, &(ptr->left))
Else
If item > ptr->info
Call del_node(item, &(ptr->right))
Else
Set save=ptr
If save-> right=NULL
Set ptr=save->left
De-allocate save
Else
If save-> left=NULL
Set ptr=save->right
De-allocate save
Else
Call del(&(save->left),save)
3. Exit
del(p,q)
1. If p->right != NULL
Call del(&(p->right),q)
Else
Set delnode=p
Set q->info=p->info
Set p=p->left
De-allocate delnode
2. Exit
Q32. Write the recursive algorithm for finding a node in a binary search tree. What are the
applications of a binary tree?
Ans: A Binary Search Tree is a binary tree in which the value in each node is greater than the values of nodes
in its left subtree and less than the values of nodes in its right subtree.
The recursive algorithm for finding a node in a binary search tree is as follows:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 33 of 83
Search(item,ptr)
1. if(!ptr)
a. Display “Element not found “
b. Exit
2. if item <ptr->info
a. Call search(item, ptr->left)
3. else
a. Call search(item, ptr->right)
4. Exit
The applications of a binary tree are as follows:
a. An algebraic expression can be represented with the help of a binary tree. Its pre-order traversal
represents the expression in prefix notation, inorder traversal represents the expression in infix notation and
postorder traversal represents the expression in postfix notation.
b. A binary tree can work as a decision tree.
c. It helps in finding/removing duplicates
Q33. Define B-tree and B+-tree. What is the need of B+ tree?
Ans: B-tee- A multiway tree of degree n is a general tree in which each node has n or fewer subtrees and
contains one fewer key than it has subtrees. A B-tree is a multiway search tree of order n in which each non-
root node contains atleast (n-1)/2 keys and a maximum of n-1 keys The keys have a definite order. A B-tree
grows at the root. It is used to reduce the number of disk-accesses while searching for a record whose keys are
stored in a node of B-tree.
The properties of a B-tree of order M can be specified as follows:
a. Each node has a maximum of M children and a minimum of M/2 children.
b. Each node has one fewer key than its children with a maximum of M-1 keys.
c. Keys are arranged in a definite order.
d. When a new key is to be inserted into a full node, the node is split into two nodes and the key
with the median value is inserted in the parent node. Incase the parent node is the root, a new root is created.
e. All leaves are at the same level i.e. there is no empty subtree above the level of the leaves.
B+ tree- All keys in a B+ tree are maintained in leaves and these keys are replicated in non-leaf nodes to define
path for locating individual records.
Since in a B+ tree, all the record keys are found in the leaf-nodes, after reaching a specific record key,
sequential travel of records becomes possible which is not so, in a B-tree.
Q34. What is a threaded binary tree? What are its different types? How is it represented in memory?
Ans: In the linked representation of a binary tree, at times, approximately half of the entries in the pointer fields
left and right contain NULL elements. This space can be most efficiently used by replacing these NULL entries
by some other type of information. Specifically, these NULL entries can be replaced by special pointers which
point to nodes higher in the tree. These special pointers are called threads and binary trees with such pointers
are called threaded binary trees. These threads must be distinguished in some way from ordinary pointers and
therefore in computer memory, an extra 1-bit tag field is used. There are many ways to thread a binary tree but
each threading corresponds to a particular tree-traversal. Also, a choice could be made between one-way
threading and two-way threading. For instance, in a one-way inorder traversal a thread can appear in the right
field and it points to the next node in inorder traversal. On the other hand in two-way threading, a thread
appears in the left field pointing to the inorder predecessor and also in the right field pointing to the inorder
successor.
The different types of threaded binary trees are as follows:
Left and right in-threaded
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 34 of 83
Ans: A Binary Search Tree is a binary tree in which the value in each node is greater than the values of nodes
in its left subtree and less than the values of nodes in its right subtree.
8
1
When 61 is inserted, as it is smaller than 81, it is put onto the left of 81:
8
1
6
1 , it being smaller than 81 and 61, is inserted to the left
When 52 is inserted
of 61:
81
6
1
5
2
When 90 is inserted, it being greater than 81, is inserted to the right of 81:
8
1
6 9
1 0
5
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
2 Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 35 of 83
8
1
9
6 0
1
8
5 7
2
When 88 is inserted, it being greater than 81 , less than 90 and greater than
87, it will be inserted to the right of 88
8
1
9
6 0
1
8
5 7
2 8
8
Q36. What are the ways in which a binary tree can be represented. Explain.
Ans: A binary tree can be represented using an array or a linked list.
In the linked list implementation, a node is defined with 3 fields:
information part , right pointer, pointing to the right child node and left
pointer. pointing to the left child node. The self referential structure used
for this purpose can be defined as follows :
struct node{int info;
struct node *left;
struct node *right;
};
B C
D E F
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 36 of 83
The array-representation is done using 3 parallel arrays: one for the info part, second for the address of the left
child and third for the address of the right child. The array representation for the above-mentioned tree is as
shown below:
1 C -1 2
2 F -1 -1
Root 3 A 4 1
4 B 5 6
5 D -1 -1
6 E -1 -1
Q37. Generate a binary search tree with 11 nodes whose inorder and postorder traversal is as
follows:
Inorder: D B A E C G F H
Postorder: D B E G H F C A
Ans: As, in the post-order traversal, the last node traversed is the root-node, the root-node for the tree to
be constructed is A. Further from the given inorder traversal, it can be made out that the nodes D and B are to
the left of node A and the nodes E, C,G,F,H are to the right of node A. The tree with the above-mentioned
inorder and post-order traversals is as shown below:
A
C
F
B
E
H
G
D
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 37 of 83
In external sorting some part of the data is loaded into the main memory, sorted using any internal sorting
technique and written back to the disk in some intermediate file. The process continues until all the data is
sorted.
Q40. Given the following sequence of elements: 44, 90, 55, 202, 620, 51, 17, 56. Design MAX Heap.
Ans: A max heap is one in which the value of every node is greater than its child nodes. The max-heap
construction for the given elements is as shown below:
4 9
4 0
4
4 9 20
9 0 2
0
Prepared4 By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
20
5 Ph. 0175-2205100,
5 2215100 9
4 5
5 2 5 0 5
20 4
2 4 4
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 38 of 83
20 202 62
2 0
9 5 62 5 20 5
0 5 0 5 2 5
4 62 4 9 4 9
4 0 4 0- 4 0
62 62
0 0
20 5 20 5
2 5 2 5
4 1
9 5 4 9 5
4 7
0 1 4 0 1
62 Max-heap
0 620
20
2 5
5 20 5
4 2 5
9
4
0 5 1 5
5 1
1 7 6 9 5
6 7
0 1
4
4
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 39 of 83
SECTION-C
10-mark questions
Q1. Define data-structure. What are its different types. Explain. Also specify the operations that
can be performed on data-structures?
Ans: The logical or mathematical model of a particular organization of data is called data structure. Data
structure can also be defined as Organized data + Allowed operations.
Data Structures could be divided into two types: Linear and Non-Linear.
a) Linear data-structures are those in which the elements form a sequence. i.e. each element in
the structure has a unique predecessor and a unique successor. These data structures are of the following
types:
1. Traversing- This refers to accessing all the data elements in the data-structure
one by one.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 40 of 83
2. Searching- It is the process of finding the location of a given data element in the
data structure.
3. Insertion- It means adding a new data element in the data structure.
4. Deletion- It means removing any existing data element from the data structure.
5. Sorting- It is the process of arranging all the elements in a data structure in some
logical order such as ascending or descending order.
6. Merging- It is the process of combining the elements of two data structures into a
single data structure.
Q3. What is an array? What are its different types? Explain with example. Are there any
drawbacks of an array? If so, explain.
Ans: An array is a variable which stores elements of the same data-type in continuous memory locations
referred by a single name. An array can be of two types:
One-dimensional and Multi-dimensional
One-dimensional- This is an array which has only a single dimension, i.e. the number of columns. The syntax
for its declaration is as follows:
Data-type array-name[size];
For eg: int a[5]; /*This statement creates continuous memory for 5 elements of int data-type.*/
If an array has to be initialized, it should be done with declaration:
For eg:
Int a[5]={10,20,30,40,50};
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 41 of 83
The address of the first element of the array is known as its base address. And the
array-name is equivalent to the address of the first element
.
Each element of the array is associated with a unique subscript-value , starting from 0
to size-1.
Multi-dimensional arrays: These arrays have more than one dimension. The following types of multi-dimensional
arrays are there:
i) Two-dimensional arrays: these have two dimensions. The declaration syntax is as follows:
Data-type array-name [row-size][column-size];
For eg.
float a[3][2]; Here the array a is defined with 3 rows and 2 columns
If an arrays is also being initialized at the time of declaration, the row-size need not be given.
As RAM is sequential, these arrays may be stored in row-major form or column major form.
ii) Three dimensional array: : These have three dimensions. The declaration syntax is as follows:
Data-type array-name[page-size] [row-size][column-size];
For eg.
float a[4][3][2]; Here the array ‘a’ is defined with 4 pages and each page has 3 rows and 2 columns.
Q4. Write a program for insertion of an element in an array and deletion of an element from an
array.
Ans: The program for insertion of an element in an array is as follows:
#include<stdio.h>
#include<conio.h>
#include<process.h>
int find(int[],int,int);
void main()
{ int A[50],item,n,index,i;
char ch=’y’;
clrscr();
printf(“How many elememts in the array “);
scanf(“%d”,&n);
printf(“Enter array elements”);
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 42 of 83
for(i=0;i<n;i++)
{scanf(“%d”,&A[i]);
fflush(stdin);
}
while(ch==’y’)
{ printf(“Enter element to be inserted “);
scanf(“%d”,&item);
if(n==50)
{printf(“Overflow “);
exit(0);
}
index=find(A,n,item);
for(i=n; i>index;i--)
A[i]=A[i-1];
A[index]=item;
n+=1;
printf(“Continue insertion “);
ch=getchar();
fflush(stdin);
}
for(i=0;i<n;i++)
printf(“%d “,A[i]);
getch();
}
int find( int A[], int size, int item)
{ int pos,i;
if(item<A[0])
pos=0;
else
{ for(i=0;i<size-1;i++)
{ if(A[i]<=item && item < A[i+1])
{pos=i+1;
break;
}
}
if(i==size-1)
pos=size;
}
return pos;
}
#include<stdio.h>
#include<conio.h>
#include<process.h>
int find(int[],int,int);
void main()
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 43 of 83
{ int A[50],item,n,index,i;
char ch=’y’;
clrscr();
printf(“How many elememts in the array “);
scanf(“%d”,&n);
printf(“Enter array elements”);
for(i=0;i<n;i++)
{scanf(“%d”,&A[i]);
fflush(stdin);
}
while(ch==’y’)
{ printf(“Enter element to be deleted “);
scanf(“%d”,&item);
if(n==0)
{ printf(“underflow “);
exit(0);
}
index=find(A,n,item);
if(index!=-1)
A[index]=0;
else
{printf(“Element does not exist “);
getch();
exit(0);
}
for(i=index;i<n;i++)
{ A[i]=A[i+1];
}
n-=1;
printf(“Delete more elements “);
ch=getchar();
fflush(stdin);
}
for(i=0;i<n;i++)
printf(“%d “,A[i]);
getch();
}
int lsearch(int A[],int size, int item)
{ int i;
for(i=0;i<size;i++)
{ if(A[i]==item)
return i;
}
return -1;
}
Q5. What is the difference between calling a function by value and by reference? What is the
need of using call by reference method? Explain with the help of an example.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 44 of 83
Ans: Call by value method: Under this method of calling a function, the parameters are passed into a
function by value. As the function has the limitation of returning back only a single value to the calling function,
more than one changed values are not available in the calling function. Eg. of calling a function by value:
void add(int,int);
void main()
{ int x,y;
x=10;
y=20;
add(x,y);
}
void add(int a , int b)
{ int c =a+b;
}
Call by reference:In this approach the addresses of the actual arguments are passed as parameters to the
called function. In this way processing is done on the addresses of the variables, so any changes made in the
called function are visible to the calling function. This method of calling a function is needed when more than
one changed values in the called function have to be reflected back in the called function. For eg:
#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;
}
When more than one changed values of the parameters passed into a function have to be available in the
calling function, the call by value method doesn’t do the needful, and call by reference method needs to be
used. This is explained by the under-mentioned program:
/* 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;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 45 of 83
printf(“a is %d”,a);
printf(“b is %d”,b);
}
Output:
a=11
b=21
a=10
b=20
Here, the changed values of a and b in the function add are not available in main.
/* 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;
*b= *b+1;
}
Output:
a=11
b=21
Here, the changed values of a and b in the function add are available in main.
Q6. Write a program to implement a structure student with fields-roll number, name and marks in
three subjects. The program reads the data for 5 students using array of structures. Reverse the list of
students using array of pointers.
Ans : The program is as follows:
#include<stdio.h>
#include<conio.h>
struct student{
int rno;
char name[20];
int marks[3];
};
void main()
{struct student s[5],*p[5],*t;
int i,j;
clrscr();
printf("Enter details\n");
for(i=0;i<=4;i++)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 46 of 83
{printf("Rno ");
scanf("%d",&s[i].rno);
fflush(stdin);
printf("Name ");
gets(s[i].name);
fflush(stdin);
for(j=0;j<=2;j++)
{ printf("Marks %d ",j+1);
scanf("%d",&s[i].marks[j]);
fflush(stdin);
}
}
for(i=0;i<=4;i++)
p[i]=&s[i];
for(i=0,j=4;i<2;i++,j--)
{ *t=*p[i];
*p[i]=*p[j];
*p[j]=*t;
}
for(i=0;i<=4;i++)
{printf("\nRno ");
printf("%d\n",s[i].rno);
printf("Name ");
printf("%s\n",s[i].name);
for(j=0;j<=2;j++)
{ printf("\nMarks %d ",j+1);
printf("%d ",s[i].marks[j]);
}
}
getch();
}
Q7. What is the difference between static and dynamic memory allocation?Explain with example.
What is memory leak?
Ans: Static memory allocation refers to memory allocation at compile-time. For example an array is
allocated memory at compile time. That is, the size of the array can not be changed at run-time.
Dynamic memory allocation means allocating memory at run time from the heap portion of RAM. At
run-time, depending upon the user’s requirement, memory can be allocated, resulting in a better utilization of
memory.
The functions generally used for this are:
malloc
malloc requires one argument - the number of bytes to be allocated dynamically.
If the memory allocation is successful, malloc returns a void pointer – this can be assigned to a pointer
variable, which will store the address of the allocated memory.
If memory allocation fails , malloc returns a NULL pointer.
Example:
int *ptr;
ptr = malloc(sizeof(int));
calloc
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 47 of 83
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 blocks to be allocated memory for. The second is the
size of each block. calloc is used to allocate multiple memory blocks.
Like malloc, calloc returns a void pointer if the memory allocation was successful, else it returns a NULL pointer.
int *ptr;
ptr = calloc(3, sizeof(int));
realloc
If the space allocated is not sufficient, reallocation of space is possible using this function
free
This function is used to de-allocate the memory block which is no longer needed.
Static memory allocation is faster than dynamic. But in static memory allocation,
memory may be wasted or there may be a shortage of memory. On the other
hand, incase of dynamic memory utilization, only as much memory is allocated
as is needed. Thus it results in better memory utilization.
A memory leak occurs when memory is allocated using malloc() function and not
released using free() function. This results in an orphaned block which is not
referenced by anything. Memory leak arises due to the following reasons:
a. Memory blocks allocated are not released even when not required.
b. The free statement is bypassed at the time of execution of the particular function.
c. The memory allocated by malloc function is stored in a pointer variable which was already
pointing to another memory location.
Q8. What is a single linked list? How is it implemented? What are its advantages over an array?
Ans: Single linked list: It is a linked list which has a single link(pointer) which is the address of the next node.
Memory representation of linked list
1. Array representation: This is done with the help of two parallel arrays. The first array stores the
information part and the second array stores the address of the next node.
info next
start 40 0
30 1
10 5
20 2
In the diagram above, the pointer start contains the position of the first element in the linked list which is 3. At
the position 3 of the array—next, the number 5 indicates the position of the next element. A 0 in the array, next,
indicates the end of the linked list, i.e. there are no further elements.
2. Dynamic representaion: In this representation, nodes are created for the linked list at run-time using
memory allocation function, malloc(). The nodes are created from the memory area known as heap.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 48 of 83
The representation of a node in the linked list is done using the following self-referential structure:
struct node{ int info;
struct node *next;
};
Advantages of linked lists over arrays:
1. As memory allocation is done at run-time, using a linked-list, results in better
memory utilization. This is because we end-up creating only as many nodes as
required by the user. Neither there is a wastage of memory nor a shortage which
might happen incase of arrays.
2. As in a linked list the nodes are not allocated continuous memory, again this results in better
memory utilization.
3. Insertion/Deletion is simpler and less time consuming as this requires only the adjustment of some
pointers. In an array, this process takes time as it requires a shifting of elements.
Q9. Write a program to show insertion in a single linked list at a specific position. What are the
operations that can be performed on it?
Ans: The program for insertion in a single linked list at a specific position is as follows:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
int count(struct node*);
void main()
{
int i,pos,n;
struct node *start,*ptr,*nptr;
char ch='y';
clrscr();
start=NULL;
while(ch=='y')
{printf("enter position");
scanf("%d",&pos);
fflush(stdin);
n=count(start);
if(pos==0||pos>n+1)
{
printf("position incorrect ");
getch();
exit(0);
}
nptr=malloc(sizeof (struct node));
printf("enter value");
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 49 of 83
scanf("%d",&nptr->info);
fflush(stdin);
nptr->next=NULL;
if(start==NULL)
start=nptr;
else
{
if(pos==1)
{
nptr->next=start;
start=nptr;
}
else
{
i=1;
ptr=start;
while(i<pos-1)
{
ptr=ptr->next;
i++;
}
if(ptr->next==NULL)
ptr->next=nptr;
else
{
nptr->next=ptr->next;
ptr->next=nptr;
}
}
}
printf("insert another node");
ch=getchar();
fflush(stdin);
}
ptr=start; //Display
while(ptr!=NULL)
{
printf("%d",ptr->info);
ptr=ptr->next;
}
getch();
}
int count(struct node*st)
{int c=0;
struct node*ptr=st;
if(ptr==NULL)
return 0;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 50 of 83
else
{while(ptr!=NULL)
{c++;
ptr=ptr->next;
}
return c;
}
}
Traversing- This refers to accessing all the nodes in the linked list one by one.
Searching- It is the process of finding the location of a given data element in the linked list. If
Binary search has to be performed, linked lists are not suitable for this searching process.
Insertion- It means adding a new data element to the linked list. This could be done in sorted or
unsorted order.
Deletion- It means removing any existing data element from the linked list.
Sorting- It is the process of arranging all the elements in some logical order such as ascending or
descending order.
Merging- It is the process of combining the elements of two linked lists into a single linked list.
Q10. Write an algorithm and program for insertion from the beginning of a single linked list.
Ans : The algorithm for insertion in a single linked list is as follows:
InsertFirst(start,item)
1. nw=malloc [Set memory for new node]
2. Set nw->info=item
3. nw->link=NULL
4. if (start=NULL)
a. Set start=nw
5. else
a. nw->link=start
b. start=nw
6. Exit.
The program for insertion in a single linked list is as follows:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
struct node{ int info;
struct node *link;
}*start,*nw,*ptr;
void main()
{ char ch=’y’;
int item;
while(ch==’y’)
{ printf(“Enter value to be inserted”
scanf(“%d”,&item);
fflush(stdin);
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 51 of 83
insertbeg(item);
printf(“Enter another node?”);
ch=getchar( );
fflush(stdin);
}
printf(“\n Displaying….\n”);
ptr=start;
while(ptr!=NULL)
{printf(“%d “,ptr->info);
ptr=ptr->link;
}
getch( );
}
void insertbeg(int item)
{ nw=malloc(sizeof(struct node));
if(nw==NULL)
{printf(“Overflow “);
getch();
exit(0);
}
nw->info=item;
nw->link=NULL;
if(start==NULL)
start=nw;
else
{ nw->link=start;
start=nw;
}
}
Q11. What is a circular linked list? How is it advantageous over a single linked list? Write an
algorithm for insertion from the beginning of a circular linked list.
Ans: A circular linked list is one in which the last node of the list rather than containing a NULL, contains the
address of the starting node. Thus the last node points back to the start of the linked list.
It is advantageous over a single linked list as reaching any node in the list, the entire list could be traversed. We
can reach any of its predecessor nodes. This is because when we traverse a circular linked list starting with a
particular node, we come back to the same node at the end.
The process of creation of a node in a circular list is the same as in a single linked list
The algorithm for insertion from the beginning of a circular linked list is as follows:
insert_beg(start,n)
a. nptr=malloc
b. nptr->info=n
c. nptr->next=NULL
d. if(start=NULL)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 52 of 83
a. start=nptr
b. start->next=start
e. else
a. set ptr=start
b. while ptr->next != start
i. ptr=ptr->next
c. nptr->next=start
d. start=nptr
e. ptr->next=start
f. Exit
Q12. What is a double linked list? What are its advantages/ disadvantages? Write the algorithm
for traversal?
Ans: In a double linked list. each node contains information part and two pointers , one containing the address
of the next node and the other containing the address of the previous node. Rather than a single pointer
pointing to the next node in a single linked list, it has two pointers, hence it is known as double linked list.
A node in a double linked list is represented using the following self-referential structure:
struct node{int info;
struct node*prev;
struct node *next;
};
It has a pointer start pointing to the beginning of the list and a pointer last pointing to the last node of the list.
This list is advantageous as it easily allows both forward and backward traversal while in a single linked only
forward traversal is possible. Since it allows both forward and backward traversals, it is also known as a double
linked list. Also reaching any specific node, we can move to its next node or to its previous node, as needed.
Its disadvantage is that it needs an extra pointer thus resulting in some extra memory being used.
3. Exit
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 53 of 83
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 54 of 83
printf(“Insufficient nodes”);
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;
clrscr();
add(&p,33);
add(&p,12);
add(&p,9);
display(p);
getch();
del(&p,2);
display(p);
getch();
}
Q14. Using array implementation of a stack, write a program showing push and pop operations.
Ans: Stack is a linear data-structure, also known as a LIFO data-structure as the last item pushed onto the
stack is the first one to be out. The insertion operation is known as push and deletion operation is known as
pop. Both these operations take place from beginning in a stack.
The program showing push and pop operations on a stack is as follows:
#include<stdio.h>
#include<conio.h>
#define max 10
int top=-1;
int stack[max];
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 55 of 83
void push(int x)
{
if(top==max-1)
{
printf(“Overflow”);
exit(0);
}
top=top+1;
stack[top]=x;
}
int pop()
{ int n;
if(top==-1)
{
printf(“Underflow”);
exit(0);
}
n=stack[top];
top=top-1;
return n;
}
void display()
{
int i;
for(i=top;I>=0;I--)
{
printf(“%d\n”,stack[i]);
}
}
void main()
{ int n;
push(3);
push(56);
push(12);
display();
n=pop();
printf(“%d”,n);
display();
getch();
}
Q15. What are the applications of a stack? Explain any one of them with the help of a program.
Ans: Stack is a linear data-structure, also known as a LIFO data-structure as the last item pushed onto the
stack is the first one to be out. The insertion operation is known as push and deletion operation is known as
pop. Both these operations take place from beginning in a stack.
The applications of a stack are as follows :
1. Enabling recursion
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 56 of 83
A stack is used to convert infix to post fix expression. The program for it, is as mentioned below:
#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;
clrscr();
printf(“enter infix expr “);
scanf(“%s”,ie);
printf(“\noriginal exp=%s”,ie);
i=strlen(ie);
ie[i]=’)’;
i=0;
s[t]=’(‘;
while(t!=-1)
{
if(ie[i]==’+’||ie[i]==’-‘||ie[i]==’*’||ie[i]==’/’)
{
if(t==0)
{ t++;
s[t]=ie[i];
}
else
{
if(ie[i]==’*’||ie[i]==’/’)
{while(s[t]==’*’||s[t]==’/’)
{pe[k]=s[t];
k++;
t--;
}
t++;
s[t]=ie[i];
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 57 of 83
}
else
{
while(s[t]==’*’||s[t]==’/’||s[t]==’+’||s[t]==’-‘)
{
pe[k]=s[t];
k++;
t--;
}
t++;
s[t]=ie[i];
}
}
}
else
if(ie[i]==’(‘)
{ t++;
s[t]=ie[i];
}
else
if(ie[i]==’)’)
{
while(s[t]!=’(‘)
{
pe[k]=s[t];
k++;
t--;
}
t--;
}
else
{
pe[k]=ie[i];
k++;
}
i++;
}
pe[k]=’\0’;
printf(“\n postfix exp=%s”, pe);
getch();
}
Q16. Show the conversion of the following expression from infix to postfix using an algorithm.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 58 of 83
A+(B*C-(D/E ↑ F) *G)*H
Ans: A stack is used to convert infix to postfix expression. The algorithm for it is as mentioned below:
Convert(top, I, P) [ I is an infix expression and P is a postfix expression]
1. Add ‘)’ to the end of I and push ‘(‘ onto the stack
2. Repeat the steps 3 to 6 till the stack gets empty
3. If a ‘(‘ is encountered:
i. Push it onto the stack
4. If an operand is encountered
i. Add it to P
5. If an operator is encountered
i. Pop from the stack each operator with higher or same precedence and add it to P
ii. Push the operator onto the stack
6. If a ‘)’ is encountered
i. Pop from the stack each operator and add it to P till ‘(‘ is encountered
ii. Remove ‘(‘
7. Exit
8.
Using the above mentioned algorithm to convert the given infix expression to postfix:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 59 of 83
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
void push(struct node **top,int num)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 60 of 83
{
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;
}
}
int pop(struct node **top)
{ int item;
struct node *temp;
if(top==NULL)
{
printf(“Underflow”);
exit();
}
item=(*top)->data;
*top=(*top)->link;
free(temp);
return item;
}
void main()
{
int n;
struct node *p;
clrscr();
p=NULL;
push(&p,14);
push(&p,23);
push(&p,67);
display(p);
n=pop(&p);
printf(“\nelement popped out is %d\n”,n);
display(p);
getch();
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 61 of 83
front=front+1;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 62 of 83
}
void display()
{
int i;
for(i=front ;i<=rear;i++)
{
printf("%d ",q[i]);
}
}
void main()
{
clrscr();
insertq(23);
insertq(6);
insertq(21);
display();
deleteq();
printf("\nafter deletion \n");
display();
getch();
}
The output of the above program is:
23 6 21
after deletion
6 21
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 63 of 83
a. Display “Underflow”
b. Exit
2. Set item=front->info
3. Set ptr=front
4. If front=rear
a. Set front=rear=NULL
5. else
a. Set front =front->next
6. De-allocate ptr
7. Display “the deleted element is “ ,item
8. Exit
#include<stdio.h>
#include<conio.h>
#define max 5
int cq[max];
int front =-1,rear=-1;
void insert(int n)
{
if((front==0 && rear==max-1)||(rear+1==front))
{printf("underflow");
getch();
return;
}
else
if(front==-1)
{front=rear=0;
cq[rear]=n;
}
else if(rear==max-1)
{ rear=0;
cq[rear]=n;
}
else
{rear++;
cq[rear]=n;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 64 of 83
}
}
void del()
{if(front==-1)
{printf("Underflow");
getch();
return;
}
else
if(front==rear)
front=rear=-1;
else
if(front==max-1)
front=0;
else
front++;
}
void disp()
{int i;
if(front==-1)
{printf("Underflow");
getch();
return;
}
if(rear>=front)
{
for(i=front;i<=rear;i++)
printf("%d ",cq[i]);
}
else
{
for(i=front;i<=max-1;i++)
printf("%d ",cq[i]);
printf("<- ");
for(i=0;i<=rear;i++)
printf("%d ",cq[i]);
}
getch();
}
void main()
{ clrscr();
insert(1);
insert(2);
insert(3);
del();
insert(4);
insert(5);
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 65 of 83
del();
disp();
}
Insertrear
1.1. If front==0 and rear=max-1
1.1.1. Write “Overflow”
1.1.2. Exit
1.2. Read item
1.3. if front=-1
1.3.1. front=rear=0
1.3.2. DQ[front]=item
1.3.3. Exit
1.4. if rear=max-1
1.4.1. I=front-1
1.4.2. while I < rear
1.4.2.1. DQ[I]=DQ[I+1]
1.4.2.2. I=I+1
1.4.3. DQ[rear]=item
1.4.4. front=front-1
1.5. else
1.5.1. rear=rear+1
1.5.2. DQ[rear]=item
1.6. Exit
Insertfront
1.1. If front==0 and rear=max-1
1.1.1. Write “Overflow”
1.1.2. Exit
1.2. Read item
1.3. if front =-1
1.3.1. front=rear=0
1.3.2. DQ[front]=item
1.3.3. Exit
1.4. if rear != max-1
1.4.1. num_item=rear-front+1
1.4.2. I=rear+1
1.4.3. j=1
1.4.4. while j<=num_item
1.4.4.1. DQ[I]=DQ[I-1]
1.4.4.2. I=I-1
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 66 of 83
1.4.4.3. j=j+1
1.4.5. DQ[I]=item
1.4.6. front=I
1.4.7. rear=rear+1
1.5. else
1.5.1. front=front-1
1.5.2. DQ[front]=item
1.6. Exit
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 67 of 83
{
struct node *q;
q=(struct node*)malloc(sizeof(struct node));
if(q==NULL)
{
printf(“Overflow”);
exit();
}
q->data=item;
if(*f==NULL)
{*f=q;
*r=q;
q->link=*f;
}
else
{(*r)->link=q;
q->link=*f;
*r=q;
}
}
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;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 68 of 83
do
{
printf(“%d\n”,q->data);
q=q->link;
} while(q!=f);
}
void main()
{
Figure 1
A
B
C
D E
G
F
a: Root node- The node at the top of the tree having no parent, is called the root node. For eg. in the
tree above, A is the root node.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 69 of 83
b: Sibling nodes- The nodes having the same parent are known as siblings. For eg. nodes D and E
are siblings as they have a common parent, B.
c: Ancestor and descendant nodes-- The parent of a node or the parent of parent is called an
ancestor. For eg. in the above-mentioned binary tree, nodes B and A are the ancestors of node D. The child of a
node or the child of the child node, is known as a descendant. If the descendant belongs to the left subtree, it is
known as the left descendant and if it belongs to the right subtree, it is known as the right descendant. For eg.
nodes D, E and F are the descendants of node B.
d: Depth(or height) of a binary tree - It is the highest level number of any node in the binary tree. In
the above-mentioned tree, the depth of the tree is 3.
e: Strictly binary tree - It is a binary tree in which every node has either 0 or 2 child-nodes.
A
Strictly binary tree
B
C
D E
f: Internal and external nodes- The nodes having child nodes are called internal/non-terminal nodes
whereas the nodes having no child nodes are called leaf/external/terminal nodes. For eg. in Figure 1 above, the
nodes A, B, C, D are internal nodes whereas the nodes E, F and G are external nodes.
g: Complete binary tree- It is a binary tree in which each level has the maximum number of nodes
and all the leaf nodes of the tree are at the same level.
At any level n of a binary tree, there can be at the most 2n nodes. i.e.:
At n=0, there can be at most 20 =1 node
At n=1, there can be at most 21 =2 nodes
At n=2, there can be at most 22 =4 nodes
and so on..
A
C
B
D E F G
h: 2-tree- Any strictly binary tree can be represented as an 2- tree by representing the leaf nodes in
square shapes. It is also known as extended binary tree.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 70 of 83
A
B
C
D E
i: Degree of a node--It is the number of child-nodes which a node has. For eg. in the tree given in
Figure 1 above, the degree of node B is 2, degree of node C is 1. Degree of nodes F, E and G is 0.
j: Path-- It is a sequence of edges between two nodes. For eg. in Figure 1 above, path from A to F is
A->B->D->F
Q25. Define binary search tree. Write the program for insertion into a binary search tree.
Ans: It is also known as binary sorted tree. It is a binary tree in which for each node, the values of nodes in its
left subtree are less the node-value and the values of nodes in its right subtree are greater than the node-value.
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node{int info;
struct node *left;
struct node *right;
}*root,*ptr,*loc,*par,*save,*nw,*suc,*parsuc;
void find(int);
void display(struct node*);
void main()
{
char ch='y';
int n;
clrscr();
root=NULL;
while(ch=='y')
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 71 of 83
{ printf("Enter no");
scanf("%d",&n);
fflush(stdin);
find(n);
if(loc!=NULL)
{printf("Number already exists ");
getch();
}
else
{nw=malloc(sizeof(struct node));
nw->info=n;
nw->left=NULL;
nw->right=NULL;
if(par==NULL)
root=nw;
else if(n<par->info)
par->left=nw;
else
par->right=nw;
}
printf("Enter another node");
ch=getchar();
fflush(stdin);
}
display(root);
getch();
}
void find(int n)
{ if(root= =NULL)
{loc=NULL;
par=NULL;
return;
}
if(n= =root->info)
{loc=root;
par=NULL;
return;
}
if(n<root->info)
{ptr=root->left;
save=root;
}
else
{ptr=root->right;
save=root;
}
while(ptr!=NULL)
{if(n= =ptr->info)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 72 of 83
{loc=ptr;
par=save;
return;
}
if(n<ptr->info)
{save=ptr;
ptr=ptr->left;
}
else
{save=ptr;
ptr=ptr->right;
}
}
loc=NULL;
par=save;
}
void display(struct node*p)
{
if(p!=NULL)
{ printf("%d ",p->info);
display(p->left);
display(p->right);
}
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 73 of 83
display(p->right);
}
}
Q27. Write the algorithm for bubble-sort. For the following sequence of elements 70,66,40,88,22
perform bubble-sort.
Ans: The algorithm for bubble-sort is as follows:
In the second iteration, the 0th and 1st elements are compared and since 40 is smaller, 66 and 40 are swapped.
After this, 66 and 70 are compared but no swapping is done. Further 70 and 22 are compared and a swapping
is done. Thus the second-largest element takes its position after the 2 nd iteration and this iteration stops here.
The sequence of elements becomes:
40,66,22,70,88
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 74 of 83
In the third iteration, 40 and 66 are compared but no swapping is done.. Then 66 and 22 are compared and
swapped. The third iteration ends here. And starting from the end, three elements have already been put in their
proper positions. The sequence of elements becomes:
40,22,66,70,88
In the last iteration, 0th and 1st position elements are compared i.e. 40 is compared with 22 and interchanged.
The sequence of elements becomes:
22,40,66,70,88
Q28. Write the program for insertion-sort. For the following sequence of elements perform
insertion-sort. 25, 17, 31, 13, 2
while(t<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=t;
}
for(i=1;i<=10;i++)
printf(" %d",a[i]);
getch();
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 75 of 83
In the second iteration, 17 is compared with 25 and since 25 is bigger than 17, 17 is compared with INT_MIN,
but as 17 is bigger, the position of 17 is 1st in the array now and the sequence of elements becomes:
INT_MIN,17,25,31,13,2
In the third iteration, 31 is compared with 25 and since 31 is bigger, its position remains the same and the
sequence of elements doesn’t change.
In the fourth iteration, the next element 13 is picked up and compared with the elements previous to it, unless it
comes across an element smaller than it, which is INT_MIN. So, 13 is inserted after the position of INT_MIN,
and the sequence of elements becomes:
INT_MIN,13,17,25,31,2
In the last iteration, 2 is similarly compared with its previous elements and in this case also all elements are
bigger than 2 till it comes across INT_MIN. So, 2 is also inserted after the position of INT_MIN, and the
sequence of elements becomes:
INT_MIN,2,13,17,25,31
Q29. Write the algorithm for quick-sort. Given the following sequence of elements, place the first
element at its correct position, using quick-sort:
44, 33, 11, 55, 77, 90, 40, 60, 99, 22, 88, 66
Ans.
The algorithm for quick-sort is as follows:
Quicksort(A, beg, end)
1. if(beg<end) then
1. loc=Partition(A, beg, end)
2. Quicksort(beg,loc-1)
3. Quicksort(loc+1,end)
2. exit
Partition(A, left, right)
1. loc=left
2. p=A[left]
3. Repeat steps 4 to 6 while left <right
4. while(A[left]<=p) and (left<right)
a. left=left+1
5. while(A[right]>p)
a. right=right-1
6. if(left<right) then
a. swap(A[left],A[right])
7. swap(A[right],A[loc])
8. loc=right
9. return loc
10.
The steps in finding the position of 44 are as follows:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 76 of 83
44, 33, 11, 55, 77, 90, 40, 60, 99, 22, 88, 66
Beginning with the last number 66, scan the list from right to left, 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
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.
Q30. Explain the different searching techniques. Give the advantages and disadvantages of these
techniques.
Ans:
Searching is the process of finding data from a set of given data items. The different searching techniques are
as follows:
Linear Search
Binary Search
Hashing
Linear Search: The linear search is a 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.
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
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 77 of 83
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. The data-structure, arrays are best
suited for performing binary search.
Linear search is a simple method in which each element of the array is compared with the number to be
searched. However, if the size of the array is big, and the number to searched is towards the end, this is a time-
consuming method. Since binary search begins with the middle-element, it reduces the number of comparisons
needed to search an element and thereby is much faster than linear search, especially where the size of the
array is big.
However binary search requires that the array should be sorted and the computation of finding the middle-most
element should be easy. These pre-requisites are not needed incase of linear search and thus for performing
linear search, the data-structure could be an array or even a linked list. However, binary search is best suited
for arrays.
Hashing- This is another method of searching in which the key of the record to be searched is mapped to the
record address. The function that transforms a key into a table-index is known as hash function. The commonly
used hash functions are: Division method, Mid-Square method, Folding Method.
The disadvantage of hashing is that it may lead to collision where-in two record keys are hashed into the same
position. To avoid this, other techniques need to be used.
However if the hash function is easy and quick to compute and leads to minimum collision, this is a very fast
method for record-search.
Q31. What is a max heap? Write the algorithm for performing heap-sort.
Ans: A binary heap is a heap data structure created using a binary tree. It is called a max heap when it satisfies
the following properties:
1) Shape Property: The tree is a complete binary tree. That is all levels of the tree, except possibly the last
one are fully filled.
2) Heap Property: Each node is greater than or equal to each of its children, i.e. the value of each node is
greater than the values of nodes in its left subtree as well as the right subtree.
Heapsort(A,N)
1. Repeat for J=1 to N-1
a. Call Insheap(A,J,A[J+1]
2. Repeat while N>=1
a. Call Delheap(A,N,Item)
b. A[N+1]=Item
Insheap(A,N,Item)
1. N=N+1
2. ptr=N
3. Repeat steps 4 to 7 while ptr>1
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 78 of 83
4. par=ptr/2
5. If item<=A[par] then
a. A[ptr]=Item
b. return
6. A[ptr]=A[par]
7. ptr=par
8. A[1]=Item
9. Return
Delheap(A,N,Item)
1. Set Item = A[1]
2. last=A[N]
3. N=N-1
4. ptr=1
5. left=2
6. right=3
7. Repeat steps 8 to 13 while right<=N
8. If last>= A[left] and last > A[right] then
a. A[ptr]=last
b. return
9. If A[left]>= A[right]
a. A[ptr]=A[left]
b. ptr=left
10. else
11. If A[right]> A[left]
a. A[ptr]=A[right]
b. ptr=right
12. left=2*ptr
13. right=left+1
14. If left= N and if last < A[left]
a. A[ptr]=A[left]
b. ptr=left
15. A[ptr]=last
16. return
#include<stdio.h>
#include<conio.h>
void mergesort(int beg,int end);
void merge(int beg,int mid,int end);
int a[10]={310,285,179,652,351,423,861,254,450,520};
void main()
{int i;
mergesort(0,9);
clrscr();
for(i=0;i<=9;i++)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 79 of 83
printf("%d ",a[i]);
getch();
}
void mergesort(int beg,int end)
{ int mid;
if(beg<end)
{ mid=(beg+end)/2;
mergesort(beg,mid);
mergesort(mid+1,end);
merge(beg,mid,end);
}
}
void merge(int beg,int mid,int end)
{int i=beg,j=mid+1,k=beg;
int b[10];
while(i<=mid && j<=end)
{if(a[i]<=a[j])
{b[k]=a[i];
i++;
k++;
}
else
{b[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{b[k]=a[i];
i++;
k++;
}
while(j<=end)
{b[k]=a[j];
j++;
k++;
}
for(k=beg;k<=end;k++)
a[k]=b[k];
}
Q33. What are the steps to delete a node in BST? Write the C-function for deletion of a node.
Ans:
To delete a node from a binary search tree, there are four cases to consider:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 80 of 83
After deletion
The C-function for deleting a node from a binary search tree is as follows:
root, loc,par,ptr and root are global pointers of tree node-type of structure
void del(int n)
{ struct node *loc;
loc=find(n);
if(loc==NULL)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 81 of 83
void find(int n)
{ if(root==NULL)
{loc=NULL;
par=NULL;
return;
}
if(n==root->info)
{loc=root;
par=NULL;
return;
}
if(n<root->info)
{ptr=root->left;
save=root;
}
else
{ptr=root->right;
save=root;
}
while(ptr!=NULL)
{if(n==ptr->info)
{loc=ptr;
par=save;
return;
}
if(n<ptr->info)
{save=ptr;
ptr=ptr->left;
}
else
{save=ptr;
ptr=ptr->right;
}
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 82 of 83
loc=NULL;
par=save;
}
if((*par)!=NULL)
{
if((*loc)==(*par)->left)
(*par)->left=child;
else
(*par)->right=child;
}
else
root=child;
}
void caseb()
{
struct node *ptr,*save,*suc,*parsuc;
ptr=loc->right;
save=loc;
while(ptr->left!=NULL)
{save=ptr;
ptr=ptr->left;
}
suc=ptr;
parsuc=save;
casea(&suc,&parsuc);
if(par!=NULL)
{
if(loc==par->left)
par->left=suc;
else
par->right=suc;
}
else
root=suc;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 83 of 83
suc->left=loc->left;
suc->right=loc->right;
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100