SlideShare a Scribd company logo
1 of 83
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 1 of 83
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.
Section – A 1 Marks Questions
[QUESTIONS 1 TO 141] [PAGE 1 TO 14]
MULTIPLE CHOICE OBJECTIVE TYPE QUESTION
Q1. Which out of these is a non-linear data-structure:
a. arrays b.linked-lists
c. queues d. tree
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
Q3. The different types of arrays are:
a. One & Multi-dimensional b. int and float
c. int,char,float d. One & Two dimensional
Q4. An array is passed into a function:
a. by value b. by reference
c. element by element d. Any 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
Q7. An uninitialized pointer is known as:
a. dangling pointer b. NULL pointer
c. generic pointer d. None of the above
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
Q9. The arithmetic operation performed on pointer variables:
a. multiplication of an integer with pointer b. addition of two pointers
c. subtraction of two pointers d. addition of a float to a pointer
Q10. Two ways to access elements of an array are:
a. by value and by reference b. indexed and pointer notation
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 2 of 83
c. sequential and random d. none of the above
Q11. The functions used for dynamic memory allocation are:
a. delete and free b. free and realloc
c. malloc and free d. malloc and calloc
Q12. An array can be categorized as which type of data-structure:
a. dynamic b. static
c. int/char/float d. multi-dimensional
Q13. The function used in C to de-allocate a memory block is:
a. delete b. free
c. malloc d. realloc
Q14. A collection of elements of different data-types is known as:
a. array b. union
c. structure d. linked list
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
Q17. A one-way list is called:
a. circular linked list b. array
c. queue d. single linked list
Q18. An orphaned block is the result of:
a. memory leak b. garbage collection
c. free function d. all of the above
Q19. A ____ pointer can point to any data-type:
a. NULL pointer b. void pointer
c. dangling pointer d. such a pointer does not exist
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
c. Hard disk d. Heap
Q23. A linked list is a linear collection of homogeneous elements called:
a. structures b. nodes
c. data d. none of the above
Q24. Insertion in a linked list can be done from:
a. beginning b. end
c. middle d. all of the above
Q25. The traversal directions possible in a double-linked list are:
a. forward b. backward
c. forward and backward d. right
Q26. A node in a double linked list comprises of:
a: information field b: information field and next pointer
c: information field, next d: information field, next pointer, previous pointer & previous pointer
pointer and thread field
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
Q32. The insertion/deletion operations on a stack are respectively known as:
a: insert and delete b: enter and exit
c: push and pop 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 4 of 83
Q33. A stack could be implemented using:
a. single and double b. single and circular
c: array and linked list d: any of the above
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
Q35. Postfix notation is also know as:
a: polish notation b: reverse polish notation
c: post notation d: post-operator notation
Q36. A linked list is which type of data-structure:
a: static b: non-linear
c: linear d: none of the above
Q37. Prefix notation is also known as:
a: polish notation b: reverse polish notation
c: pre notation d: post-operator notation
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
Q41. The condition top=-1 indicates that:
a: stack has only one element b: stack is full
c: stack is empty d: none of these
Q42. The validity of an expression containing nested parentheses could be checked using:
a: linked list b: queue
c: tree d: stack
Q43. A string could be reversed using the data-structure:
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
Q45. In a normal queue, the underflow situation occurs when:
a: rear=max -1 b: front= -1
c: rear=front d: rear=size-1
Q46. In a circular queue, one of the situations when overflow occurs:
a: rear=size-1 b: rear=front
c: (rear+1)=front d: front=-1
Q47. In postfix expression, the operator is placed:
a: in-between the operands b: after the operands
c: before the operands d: none of these
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
Q54. A non-linear hierarchical type of data-structure:
a: graph b: tree
c: array d: deque
Q55. All leaf nodes of a tree are termed as:
a: terminal nodes b: non-terminal nodes
c: child nodes d: internal nodes
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 6 of 83
Q56. The root node is
a: terminal node b: internal nodes
c: child node d: none of the above
Q57. The nodes belonging to the same parent are known as:
a: descendants b: external nodes
c: child nodes d: siblings
Q58. A tree in which the degree of each node is either 0 or 2:
a: complete binary tree b: binary search tree
c: strictly binary tree d: none of the above
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: *
Q62. In inorder traversal of a binary tree, the root node is visited:
a: after the traversal of b: before the traversal of
right & left subtrees right and left subtrees
c. in-between the traversal of d: none of these
left and right subtrees
Q63. The height of the following binary tree is:
a: 3 b: 4
c: 5 d: 2
Q64. A binary search tree is also known as:
a: B-tree b: binary sorted tree
c. binary ordered tree d: B+ tree
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
A
B
C
D E
F
G
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
Q68. The complexity of bubble-sort algorithm is:
a: O(n2
) b: O(n)
c: O(log n) d: O(n log n)
Q69. Binary search is more suitable for:
a: array b: linked list
c: stack d: any of the above
Q70. The complexity of binary-search algorithm is:
a: O(log n) b: O(n log n)
c: O(n) d: O(n2
)
Q71. The calloc() function can be used to allocate:
a: multiple blocks of memory b: single block of memory
c: two blocks of memory d: none of these
Q72. The postfix expression of the infix expression: A+B*(C+D)/F+D*E is:
a: AB+CD+*F/D+E* b: ABCD+*F/+DE*+
c: A*B+CD/F*DE++ d: A+*BCD/F*DE++
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
Q74. Which data-structure is needed to convert infix notation to postfix notation:
a: queue b: stack
c: tree d: linked list
Q75. Which of the following sorting procedures is the slowest:
a: Quick sort b: bubble sort
c: Shell sort d: insertion sort
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
Q77. If n elements are to be sorted, the complexity of selection-sort is:
a: O(1) b: O(log n)
c: O(n) d: O(n2
)
Q78. The operation of processing each element in the list is known as:
a: sorting b: merging
c: inserting d: traversal
Q79. Arrays are best data structures:
a: for relatively permanent collections b: when the size of structure is
constantly changing
c: for both the above situations d: for none of the above situations
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
Q81. Pick the odd one out:
a: insertion sort b: selection sort
c: counting sort d: merge sort
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
Q85. The searching technique suitable for unsorted arrays:
a: binary search b: linear search
c: any of these d: none of these
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
a: Big O notation b: Polish notation
c: Time notation d: space complexity
Q87. The technique of collecting unused memory is known as:
a: garbage collection b: Dynamic memory allocation
c: static memory allocation d: none of these
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
Q90. The main measures for the efficiency of an algorithm are:
a: processor and memory b: complexity and capacity
c: time and space d: data and space
Q91. Which of the following cases does not exist in complexity theory:
a: best case b: worst case
c: average case d: Null case
Q92. The worst case occurs in linear search algorithm when:
a: item is in the middle of the b: item is not in the array
array
c: item is the last element in the d: item is the last element in the
array array or not in the array at-all
Q93. The complexity of merge sort algorithm is:
a: O(n) b: O(log n)
c: O(n2
) d: O(n log n)
Q94. The complexity of linear search algorithm is:
a: O(n) b: O(log n)
c: O(n2
) d: O(n log n)
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
Q96. Linked lists are best suited:
a: for relatively permanent collections b: when the size of structure is
constantly changing
c: for both the above situations d: for none of the above situations
Q97. The memory address of the first element of an array is called:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 10 of 83
a: floor address b: foundation address
c: first address d: base address
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
Q99. Which of the following data-structures are indexed structures:
a: linear arrays b: linked lists
c: both of the above 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
Q102. Which of the following statements is false:
a: Arrays are static data structures b: data elements in linked list need
not be stored in adjacent space in
memory
c: pointer stores the next data element d: linked lists are collection of nodes
of a list that contain information part &
next pointer
Q103. Which of the following is a two-way list:
a: grounded header list b: circular header list
c: linked list with header & trailer nodes d: none of the above
Q104. The terms “push” and “pop” are related to:
a: array b: lists
c: stacks d: all of the above
Q105. The depth of a complete binary tree is given by:
a: n log n b: n log n +1
c: log n d: log n +1
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
Q107. An algorithm that calls itself directly or indirectly is known as:
a: sub-algorithm b: recursive algorithm
c: polish notation d: traversal algorithm
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
Q109. Value of first linked list index is:
a: 1 b: 0
c: -1 d: none of these
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
Q112. In a heap tree:
a: value in a node is greater than every b: value in a node is greater than
value in left subtree and smaller than the value of its child nodes
right subtree
c: both the above conditions d: none of the above conditions
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
Q115. Which of the following algorithms is of divide and conquer type:
a: bubble-sort b: insertion sort
c: quick sort d: all of the above
Q116. One of the applications of a linked list:
a: Polynomial evaluation b: Postfix expression evaluation
c: determining the distance traveled d: none of these
Q117. A tree having any number of nodes:
a: binary tree b: general 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 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
Q120. Heaps are of two types:
a: high and low b: max and min
c: B and B+ d: none of the above
Q121. Incase of min-heap, the value present in any node is:
a: greater than all its children b: smaller than all its children
c: equal to all its children d: greater than values in left subtree
and smaller than values in right
subtree
Q122. A min-heap is also known as:
a: decreasing heap b: descending heap
c: low heap d: none of these
Q123. A max-heap is also known as:
a: increasing heap b: ascending heap
c: high heap d: none of these
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
Q125. A matrix which has most of its values equal to 0:
a: sparse matrix b: zero-matrix
c: empty matrix d: none of the above
Q126. A sparse matrix can also be represented using:
a: queue b: stack
c: tree d: linked list
Q127. A B-tree grows at the:
a: root b: leaves
c: braches d: any of the above
Q128. A binary tree grows at the
a: root b: leaves
c: braches d: any of the above
Q129. Shell sort is an improvisation over:
a: quick- sort b: merge-sort
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 13 of 83
c: insertion-sort d: none of these
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
Q131. While calculating time-complexity, the program-time which is considered is:
a: compile time b: execution time
c: both compile and run-time d: none of the above
Q132. The time complexity of the following algorithm is:
sum(a,n){ s=0; for i= 1 to n{s=s+a[i]; } return s;}
a: 3n+2 b: 2n +3
c: n+1 d: 2n+2
Q133. Complexity of heap sort
a: O(n) b: O(log n)
c: O(n2
) d: O(n log n)
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
Q135. The leaf nodes of a tree have height equal to:
a: height of the tree b: zero
c: one d: none of these
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
Q137. Height of a full binary tree with n internal nodes is:
a: n log n b: n
c: n+1 d: log n
Q138. The degree of a leaf node is:
a: 1 b: 0
c: -1 d:2
Q139. A right in-threaded binary tree contains:
a: inorder successor b: inorder predecessor
c: NULL d: preorder successor
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
a: First fit b: Best fit
c: Worst fit d: Next fit
Answers
1(d) 2(b) 3(c) 4(b) 5(a) 6(a) 7(a) 8(c)
9(c) 10(b) 11(d) 12(b) 13(b) 14(c) 15(b) 16(c)
17(d) 18(a) 19(b) 20(b) 21(c) 22(d) 23(b) 24(d)
25(c) 26(c) 27(d) 28(d) 29(c) 30(c) 31(b) 32(c)
33(c) 34(d) 35(b) 36(c) 37(a) 38(c) 39(d) 40(a)
41(c) 42(d) 43(d) 44(a) 45(b) 46(c) 47(b) 48(a)
49(a) 50(a) 51(b) 52(c) 53(a) 54(b) 55(a) 56(b)
57(d) 58(c) 59(a) 60(a) 61(a) 62(c) 63(a) 64(b)
65(b) 66(a) 67(c) 68(a) 69(a) 70(a) 71(a) 72(b)
73(a) 74(b) 75(b) 76(d) 77(d) 78(d) 79(a) 80(a)
81(c) 82(b) 83(a) 84(b) 85(b) 86(a) 87(a) 88(a)
89(a) 90(c) 91(d) 92(d) 93(d) 94(a) 95(d) 96(b)
97(d) 98(a) 99(a) 100(c) 101(a) 102(c) 103(d) 104(c)
105(d) 106(a) 107(b) 108(b) 109(b) 110(a) 111(c) 112(b)
113(d) 114(c) 115(c) 116(a) 117(b) 118(a) 119(c) 120(b)
121(b) 122(b) 123(b) 124(a) 125(a) 126(d) 127(a) 128(b)
129(c) 130(b) 131(b) 132(b) 133(d) 134(b) 135(b) 136(b)
137(d) 138(b) 139(a) 140(a) 141(b)
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 n0 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
2. Write a program to merge two sorted arrays.
Ans: The program to merge two sorted arrays is as follows:
#include<stdio.h>
#include<conio.h>
void main()
{ int a[5]={10,20,30,40,50},b[5]={11,22,28,30,35},c[10],i,j,k;
for(i=0,j=0,k=0;i<=4 && j<=4;k++)
{if(a[i]<=b[j])
{c[k]=a[i];
i++;
}
else
{
c[k]=b[j];
j++;
}
}
while(i<=4)
{
c[k]=a[i];
i++;
k++;
}
while(j<=4)
{
c[k]=b[j];
j++;
k++;
}
clrscr();
for(k=0;k<=9;k++)
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.
Different operations possible on pointer variables are:
1) Addition of an integer to a pointer
2) Subtraction of an integer from a pointer
3) Subtraction of two pointers
4) Comparison of two pointers
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.
4. Explain what is meant by an array of pointers with the help of an example.
Ans: A pointer is a variable that contains the address of another variable. i.e. it points to another variable.
A pointer array or an array of pointers is a collection of pointer variables where
each pointer variable points to a specific memory location. The pointer variables
are stored in continuous memory locations. The size of this array is fixed at compile time.
It is declared in the same way as other arrays are declared except an asterik(*)
is specified before the array name.
For eg. int *ptr[3];
here ptr is an array of pointers that can store the addresses of 3 memory locations.
The array is organized in the memory as
0 1 2
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’.
5. Write a program to find the product of two matrices.
Ans: The program for multiplication of two matrices is as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
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(k=0;k<3;k++)
{
c[i][k]=0;
for(j=0;j<3;j++)
c[i][k]=c[i][k]+a[i][ j ]*b[ j ][k];
}
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 18 of 83
printf (“Result of Multiplicationn”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d”,c[i][j]);
}
printf(“n”);
}
getch();
}
6. Write a program to add two matrices.
Ans: The program for addition of two matrices is as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
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();
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 elementsn");
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=%dn",sa);
printf("Sum of elements below the main diagonal=%dn",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.
The algorithm for it, is as given below:
Reverse(start)
1. temp=start
2. ptr=NULL
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>
struct node{int info;
struct node * next;
struct node *back;
}*start,*last,*nw,*ptr,*save;
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.
11. Define a structure. What is a self-referential structure? Explain with example.
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;
};
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 36 bytes, comprising of
rno, name and marks in a sequential order.
A self-referential structure is a structure which has atleast one member which is of
the same type as the structure itself. It is different from an ordinary structure because
it has atleast one structure pointer of its own type as one of its members.
Self referential structures are needed in situations when the exact number of records to be input is not
known. With the help of these structures, linked records can be created. Unlike arrays, linked records are stored
in non-contiguous locations but are linked to each other with the help of pointers. For eg. a self-referential
structure can be declared in the following way: struct student{ int rno;
char name[30];
struct student *next;
};
The above-mentioned structure declaration contains next pointer which is of the same type as the structure
itself which is used to point to a record of the same type.
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
ii. Set temp=temp->next
4. Return count
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.
14. Name the different types of linked list?
Ans. The various types of linked list are:-
1. Single-linked list
2. Double-linked list
3. Circular linked list
4. Header linked list
Single-linked list:> A linked list whose node contains two parts i.e. information part & link part & null value in the
link part signifies last node. As it has a single link which is to the next node, it is known as single linked list.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 24 of 83
Info Link
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
Q15. Write the algorithm for reversing a string using a stack.
Ans: The algorithm for reversing string using a stack is as follows:
Reversal(top,str)
1. Set I=0
2. while(I<length_of_str)
a. Push str[I] onto the stack
b. Set I=I+1
3. Set I=0
4. while(top != NULL)
a. Pop the top element of the stack and store it in str[I]
b. Set I=I+1
5. Print “The reversed string is “ ,str
6. Exit
Q16. Write the algorithm for checking the validity of parentheses. Which data-structure is used for
this purpose.
Ans: A stack is used for the purpose of checking the validity of parentheses. The algorithm for checking the
validity of parentheses is as follows:
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
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. Else If (expr[I]=’)’ or expr[I]=’}’ or expr[I] =’]’)
i. if(top=NULL)
1. Display “invalid expression”
2. Exit
ii. else
1. Pop the top symbol from the stack and store it in c
2. if(c and expr[I] are not matching symbols)
a. Display “Invalid expression”
b. Exit
c. Set I=I+1
3. if(top != NULL)
a. Display “ Invalid epression”
4. else
a. Display “Valid expression”
5. Exit
Q17. Write the algorithm for evaluation of a postfix expression.
Ans: 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 in P until the ‘)’ is encountered.
3. If an operand is encountered, then:
a. 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. Push the result of (b) back onto the STACK
5. Set VALUE equal to the top element of STACK
6. Exit.
Q18. Convert the following expression from a.) infix to postfix and b.) infix to prefix
A * (B+C) ↑ D-E / (F+G)
Ans:
a) infix to postfix
A * (B+C) ↑ D-E / (F+G)
A*BC+ ↑ D-E /FG+
A*BC+D↑ - E / FG+
ABC+D↑* -E/FG+
ABC +D↑* - EFG+/
ABC+D↑*EFG+/- (Postfix expression)
b) infix to prefix
A * (B+C) ↑ D-E / (F+G)
A* +BC ↑ D-E / +FG
A* ↑+BCD –E/ +FG
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 26 of 83
*A↑+BCD – E / +FG
*A↑+BCD - /E+FG
-*A↑+BCD /E+FG (Prefix expression)
Q19. Differentiate between infix, postfix and prefix expressions
Ans: The general arithmetic expression is written in infix notation, containing parentheses.Because of the
precedence of operators, it involves a back and forth movement, making the evaluation difficult and time-
consuming. Therefore these expressions are converted into another notation, the evaluation of which is easier
and faster.
A Polish mathematician named Jan Lukasiewicz suggested two alternative notations to represent an arithmetic
expression. The notation in which the operator occurs before the operands is known as Prefix notation(also
known as Polish Notation). The notation in which the operator occurs after the operands is known as Postfix
notation(also known as Reverse Polish Notation).
In these notations, the operations are performed in the order in which the operators are encountered in the
expression. These expressions do not contain parentheses and while evaluating them, the precedence of
operators is insignificant. As a result they are computed faster than infix expressions.
Eg. of Infix expression: A * (B+C) ↑ D-E / (F+G)
When converted to postfix: ABC+D↑*EFG+/-
When converted to prefix: -*A↑+BCD /E+FG
Q20. Consider the following stack of size 5. Top=2.
Stack: Delhi, Kolkatta, Patiala.
Describe the stack when the following operations take place:
a. Chandigarh is pushed
b. Ahmedabad is pushed
c. Pop the element
d. Chennai is pushed
e. Lucknow is pushed
f. Pop the element
Ans: a: When operation a is performed, top becomes equal to 3 and Chandigarh is pushed onto the top of the
stack:
Stack: Delhi, Kolkatta, Patiala, Chandigarh
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:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 27 of 83
Stack: Delhi, Kolkatta, Patiala, Chandigarh, Chennai
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)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 28 of 83
1. Set temp=start, prev =start
2. Allocate memory to nptr
3. If nptr=NULL
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.
Q24. Define a queue. Specify some of the applications of a queue.
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.
Eg. - There are numerous examples of queues in our everyday life e.g. people waiting in a line at a bank,
form a queue.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 29 of 83
Typical uses of queues are in simulations and operating systems.
• 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
2. No. of elements=As rear<front: (rear+1)+(upper subscript-front +1) = (4+1)+ (9-9+1)= 5+1=6
3. No. of elements = As rear > front: rear-front+1=5-4+1=2
After two elements are deleted : no. of elements=2-2=0
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 30 of 83
Q27. Consider the following circular queue of size 5. front=0,rear=2.
Circular queue: Delhi, Kolkatta, Patiala.
Describe the queue when the following operations take place:
a. Chandigarh is inserted
b. Ahmedabad is inserted
c. An element is deleted
d. Chennai is inserted
e. Lucknow is inserted
f. An element is deleted
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.
Ans: For a normal 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
For a circular queue:
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
i. If item < ptr->info
1. Call insert_node(item, ptr->left)
ii. Else
1. Call insert_node(item, ptr->right)
3. Exit
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
Left and right pre-threaded
For representing a threaded binary tree in memory, the node contains like a normal binary tree, the fields:
information, right pointer and left pointer. However, in a threaded binary tree, the right/left pointers might contain
the addresses of right/left child nodes but if they are NULL, may respectively contain the inorder successor’s
address or inorder predecessor’s address. To specify whether, right/left pointer is containing a child node
address or successor/predecessor address, a one-bit thread field is used containing a one in the latter case.
The node representation of an right-in-threaded binary tree is as shown below:
right pointer information left thread
pointer
Q35. Create a binary search tree for the following sequence of elements.
81,61,52,90,87,88
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.
Creating a Binary search for the sequence of elements given:
When 81 is inserted, it being the first element, becomes the root node:
When 61 is inserted, as it is smaller than 81, it is put onto the left of 81:
When 52 is inserted , it being smaller than 81 and 61, is inserted to the left
of 61:
When 90 is inserted, it being greater than 81, is inserted to the right of 81:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
8
1
8
1
6
1
81
6
1
5
2
8
1
6
1
5
2
9
0
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 35 of 83
When 87 is inserted, it being greater 81 and less than 90, it should be
inserted to the left of 90:
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
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;
};
For eg. following is the linked list representation of a binary tree:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
8
1
6
1
5
2
9
0
8
7
8
1
6
1
5
2
9
0
8
7
8
8
A
B C
D E F
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:
info left right
1 C -1 2
2 F -1 -1
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:
Q38. Define sorting. Differentiate between internal and external sorting.
Ans: The process of arranging data in some logical order is known as sorting. The order can be
ascending/descending for numeric data and alphabetical for character data. There are two types of sorting
namely internal sorting and external sorting.
If all the data to be sorted fits entirely in the main memory , then internal sorting is used. There are different
kinds of internal sorting which are used viz. selection sort, bubble sort, insertion sort, etc. The choice of a
particular algorithm depends upon the properties of data and operations to be performed on the data.
If all the data to be sorted does not fit entirely in the main memory, external sorting is used. It requires the use
of external memory such as disks, tapes, during sorting.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
Root
A
B
D
C
E
F
G
H
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.
Q39. Write the program for performing binary search.
Ans : The program for performing binary search is as follows:
#include<stdio.h>
#include<conio.h>
void bin_search(int[],int,int );
void main()
{int a[10]={10,21,33,54,67,88,97,101,112,120};
int n;
clrscr();
printf("Enter the no. to be searched ");
scanf("%d",&n);
bin_search(a,10,n);
getch();
}
void bin_search(int a[],int size,int n)
{int mid,beg=0,end=size-1;
while(beg<=end)
{mid=(beg+end)/2;
if(n==a[mid])
{printf("Element found at position %d",mid+1);
getch();
return;
}
else
if(n >a[mid])
beg=mid+1;
else
end=mid-1;
}
if(beg>end)
printf("No. not found ");
return;
}
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:
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
4
4
20
2
9
0
5
5
4
9
0
4
4
9
0
4
4 5
5
20
2
9
0
20
2
5
5
4
4
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 38 of 83
Max-heap
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
20
2
9
0
5
5
4
4
62
0
202
62
0
5
5
4
4
9
0-
62
0
20
2
5
5
4
4
9
0
62
0
20
2
5
5
4
4
9
0
5
1
1
7
62
0
20
2
5
5
4
4 9
0
5
1
62
0
20
2 5
5
4
4
9
0 5
1
1
7
5
6
20
2
5
5
5
6 9
0
5
1
1
7
4
4
620
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:
i) Arrays- An array is defined as a collection of elements of the same data-type , stored in
continuous memory locations referred by a single name. The size of the array has to be specified at the time of
writing the program and memory for it is reserved at compile-time. Hence it is a static data-structure. Arrays are
of two types: one-dimensional and multi-dimensional. Multi-dimensional arrays could be : two-dimensional,
three-dimensional and so-on. Each element of the array is referred using a subscript or index. Insertion/Deletion
in an array can take place from the beginning, middle or end.
j) Linked lists- It is a dynamic data-structure in which memory for each node is allocated at
run-time from the heap portion of RAM. The memory allocation for the nodes need not be continuous as in
arrays. It can be defined as a list of nodes where each node contains the information part and the address of
the next node. Insertion/Deletion can take place from the beginning, middle or end. A linked list helps in better
memory utilization. Linked lists could be: single, double or circular.
k) Queues- It is a linear data-structure in which insertion can take place only at the end i.e.
rear and deletion can take place only in the beginning i.e. front. As the element which is first in, is first out,
therefore a Queue is known as a FIFO data-structure. For eg. implementation of a queue for cinema-tickets.
l) Stacks-This is a linear data-structure in which the insertion/ deletion takes place only at one
end which is the TOP. The insertion operation is known as PUSH and deletion operation is known as POP.
Since the element which is pushed last, is popped out first, a stack is known as a LIFO data-structure.
b) Non-Linear data-structures- These data structures are not in a sequence.
They are of the following two types:
i)Trees- To represent a hierarchical structure, a tree is used. For eg. family tree, organization structure, etc.
The node at the top which does not have a parent is called the root node. Every other node has a unique
parent. The nodes with child nodes are called internal nodes and the nodes without children are called leaves or
external nodes.
j)Graphs- It is used to represent a non-sequential, non-hierarchical structure. A graph can be defined as a
non-empty set of vertices and edges. For eg. an application needing to find the route between two cities will
need to use a graph.
Some operations which are performed on data-structures are:
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.
Q2. Write short-notes on the following:
a: Arrays b: Linked lists
c: Trees d: Graphs
Ans: a. Arrays- An array is defined as a collection of elements of the same data-type, stored in continuous
memory locations referred by a single name. The size of the array has to be specified at the time of writing the
program and memory for it is reserved at compile-time. Hence it is a static data-structure. Arrays are of two
types: one-dimensional and multi-dimensional. Multi-dimensional arrays could be : two-dimensional, three-
dimensional and so-on. Each element of the array is referred using a subscript or index. Insertion/Deletion in an
array can take place from the beginning, middle or end.
b: Linked lists- It is a dynamic data-structure in which memory for each node is allocated at run-time from
the heap portion of RAM. The memory allocation for the nodes need not be continuous as in arrays. It can be
defined as a list of nodes where each node contains the information part and the address of the next node.
Insertion/Deletion can take place from the beginning, middle or end. A linked list helps in better memory
utilization. Linked lists could be: single, double or circular.
c. Trees- To represent a hierarchical structure, a tree is used. For eg. family tree, organization structure, etc.
The node at the top which does not have a parent is called the root node. Every other node has a unique
parent. The nodes with child nodes are called internal nodes and the nodes without children are called leaves or
external nodes.
d. Queues- It is a linear data-structure in which insertion can take place only at the end i.e. rear and
deletion can take place only from the beginning i.e. front. Hence the element which is first in, is first out,
therefore a Queue is known as a FIFO data-structure. For eg. implementation of a queue for cinema-tickets.
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};
An array can also be declared without size-specification if it is initialized:
For eg: int a[]={10,20,30,40,50};/* Here the compiler will reserve memory for 5 elements as 5 element-values
have been given.*/
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.
When the array is stored row by row, it is known as row-major form.
W hen the array is stored col by col, it is known as 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.
Disadvantages of an array: An array has the following disadvantages:
a: 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.
b: For arrays, static memory allocation is used. This might result in a shortage of memory or memory
may be wasted. Thus memory may not be properly utilized.
c: Insertion and deletion of elements in an array requires a shifting of elements, thus is time-consuming.
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;
}
The program for deletion of an element from an array is as follows:
#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)
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 45 of 83
a=a+1;
b=b+1;
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 detailsn");
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 46 of 83
for(i=0;i<=4;i++)
{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("%dn",s[i].rno);
printf("Name ");
printf("%sn",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));
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
10
20
30
40
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 47 of 83
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.
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
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.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
2
1
5
0start
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 48 of 83
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.
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);
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 49 of 83
}
nptr=malloc(sizeof (struct node));
printf("enter value");
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;
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 50 of 83
struct node*ptr=st;
if(ptr==NULL)
return 0;
else
{while(ptr!=NULL)
{c++;
ptr=ptr->next;
}
return c;
}
}
The operations which can be performed on it are:
• 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’)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 51 of 83
{ printf(“Enter value to be inserted”
scanf(“%d”,&item);
fflush(stdin);
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
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 52 of 83
b. nptr->info=n
c. nptr->next=NULL
d. if(start=NULL)
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.
The algorithm for forward traversal of a double linked list is as follows:
forward(start)
1. ptr=start
2. while(ptr !=NULL)
a. Display ptr->info
b. ptr=ptr->next
3. Exit
The algorithm for backward traversal of a double linked list is as follows:
backward(last)
1. ptr=last
2. while(ptr !=NULL)
i. Display ptr->info
ii. ptr=ptr->prev
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 53 of 83
3. Exit
Q13. Write a program to implement doubly (two–way) linked list.
Ans. The program showing the implementation of a double linked list is as
follows:
#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,i;
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++)
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 54 of 83
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;
}
}
}
void display(struct node *q)
{
while(q!=NULL)
{
printf(“%dn”,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>
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 55 of 83
#define max 10
int top=-1;
int stack[max];
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(“%dn”,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.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2
Datastructure bsc2

More Related Content

What's hot

Interactive exploration of complex relational data sets in a web - SemWeb.Pro...
Interactive exploration of complex relational data sets in a web - SemWeb.Pro...Interactive exploration of complex relational data sets in a web - SemWeb.Pro...
Interactive exploration of complex relational data sets in a web - SemWeb.Pro...Logilab
 
R tools for HiC data visualization
R tools for HiC data visualizationR tools for HiC data visualization
R tools for HiC data visualizationtuxette
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programingAhammed Alamin
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010
Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010
Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010Paolo Missier
 
FINAL PAPER FP304 DATABASE SYSTEM
FINAL PAPER FP304 DATABASE SYSTEMFINAL PAPER FP304 DATABASE SYSTEM
FINAL PAPER FP304 DATABASE SYSTEMAmira Dolce Farhana
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionYu-Sheng (Yosen) Chen
 

What's hot (16)

Lec 08 - DESIGN PROCEDURE
Lec 08 - DESIGN PROCEDURELec 08 - DESIGN PROCEDURE
Lec 08 - DESIGN PROCEDURE
 
Interactive exploration of complex relational data sets in a web - SemWeb.Pro...
Interactive exploration of complex relational data sets in a web - SemWeb.Pro...Interactive exploration of complex relational data sets in a web - SemWeb.Pro...
Interactive exploration of complex relational data sets in a web - SemWeb.Pro...
 
Data structure
Data structureData structure
Data structure
 
Lecture6
Lecture6Lecture6
Lecture6
 
Trees unit 3
Trees unit 3Trees unit 3
Trees unit 3
 
Cdi implementation
Cdi implementationCdi implementation
Cdi implementation
 
Mca co qb
Mca co qbMca co qb
Mca co qb
 
R tools for HiC data visualization
R tools for HiC data visualizationR tools for HiC data visualization
R tools for HiC data visualization
 
C,C++ In Matlab
C,C++ In MatlabC,C++ In Matlab
C,C++ In Matlab
 
VLDB Phd Workshop
VLDB Phd WorkshopVLDB Phd Workshop
VLDB Phd Workshop
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programing
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010
Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010
Paper talk (presented by Prof. Ludaescher), WORKS workshop, 2010
 
FINAL PAPER FP304 DATABASE SYSTEM
FINAL PAPER FP304 DATABASE SYSTEMFINAL PAPER FP304 DATABASE SYSTEM
FINAL PAPER FP304 DATABASE SYSTEM
 
CS8391 Data Structures Part B Questions Anna University
CS8391 Data Structures Part B Questions Anna UniversityCS8391 Data Structures Part B Questions Anna University
CS8391 Data Structures Part B Questions Anna University
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
 

Similar to Datastructure bsc2

Redo midterm
Redo midtermRedo midterm
Redo midtermIIUM
 
Q1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdfQ1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdffatoryoutlets
 
Data structure - mcqs
Data structure - mcqsData structure - mcqs
Data structure - mcqssuthi
 
Ds qb 2021 rma
Ds qb 2021 rmaDs qb 2021 rma
Ds qb 2021 rmaARAVINDRM2
 
Dat 305 dat305 dat 305 education for service uopstudy.com
Dat 305 dat305 dat 305 education for service   uopstudy.comDat 305 dat305 dat 305 education for service   uopstudy.com
Dat 305 dat305 dat 305 education for service uopstudy.comULLPTT
 
Complier design one mark Q & A 50 by S. Yamini
Complier design one mark Q & A 50 by S. YaminiComplier design one mark Q & A 50 by S. Yamini
Complier design one mark Q & A 50 by S. Yaminieeducations ever
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
 
300+ top data structures and algorithms mc qs pdf 2020
300+ top data structures and algorithms mc qs pdf 2020300+ top data structures and algorithms mc qs pdf 2020
300+ top data structures and algorithms mc qs pdf 2020tadeseguchi
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.pptRahulYadav738822
 
Digital electronics revision unit4 mcq
Digital electronics revision unit4  mcqDigital electronics revision unit4  mcq
Digital electronics revision unit4 mcqSIVALAKSHMIPANNEERSE
 
C mcq practice test 4
C mcq practice test 4C mcq practice test 4
C mcq practice test 4Aman Kamboj
 
Digital electronics revision unit4 mcq
Digital electronics revision unit4  mcqDigital electronics revision unit4  mcq
Digital electronics revision unit4 mcqSIVALAKSHMIPANNEERSE
 
C programming & data structure
C programming & data structureC programming & data structure
C programming & data structurerajeev_123
 
Story of OSI models in Networking.ppt
Story of OSI models in Networking.pptStory of OSI models in Networking.ppt
Story of OSI models in Networking.pptShreeShak1
 

Similar to Datastructure bsc2 (20)

Redo midterm
Redo midtermRedo midterm
Redo midterm
 
Q1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdfQ1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdf
 
Data structure part 2
Data structure part  2Data structure part  2
Data structure part 2
 
Data structure - mcqs
Data structure - mcqsData structure - mcqs
Data structure - mcqs
 
Ds qb 2021 rma
Ds qb 2021 rmaDs qb 2021 rma
Ds qb 2021 rma
 
Dat 305 dat305 dat 305 education for service uopstudy.com
Dat 305 dat305 dat 305 education for service   uopstudy.comDat 305 dat305 dat 305 education for service   uopstudy.com
Dat 305 dat305 dat 305 education for service uopstudy.com
 
Data structure
Data structureData structure
Data structure
 
Complier design one mark Q & A 50 by S. Yamini
Complier design one mark Q & A 50 by S. YaminiComplier design one mark Q & A 50 by S. Yamini
Complier design one mark Q & A 50 by S. Yamini
 
Computer architecture PART 2
Computer architecture  PART  2Computer architecture  PART  2
Computer architecture PART 2
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
 
300+ top data structures and algorithms mc qs pdf 2020
300+ top data structures and algorithms mc qs pdf 2020300+ top data structures and algorithms mc qs pdf 2020
300+ top data structures and algorithms mc qs pdf 2020
 
linkedlist (1).ppt
linkedlist (1).pptlinkedlist (1).ppt
linkedlist (1).ppt
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
 
Digital electronics revision unit4 mcq
Digital electronics revision unit4  mcqDigital electronics revision unit4  mcq
Digital electronics revision unit4 mcq
 
C mcq practice test 4
C mcq practice test 4C mcq practice test 4
C mcq practice test 4
 
C test
C testC test
C test
 
Digital electronics revision unit4 mcq
Digital electronics revision unit4  mcqDigital electronics revision unit4  mcq
Digital electronics revision unit4 mcq
 
C programming & data structure
C programming & data structureC programming & data structure
C programming & data structure
 
Gate-Cs 2009
Gate-Cs 2009Gate-Cs 2009
Gate-Cs 2009
 
Story of OSI models in Networking.ppt
Story of OSI models in Networking.pptStory of OSI models in Networking.ppt
Story of OSI models in Networking.ppt
 

Recently uploaded

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Datastructure bsc2

  • 1. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 1 of 83 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. Section – A 1 Marks Questions [QUESTIONS 1 TO 141] [PAGE 1 TO 14] MULTIPLE CHOICE OBJECTIVE TYPE QUESTION Q1. Which out of these is a non-linear data-structure: a. arrays b.linked-lists c. queues d. tree 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 Q3. The different types of arrays are: a. One & Multi-dimensional b. int and float c. int,char,float d. One & Two dimensional Q4. An array is passed into a function: a. by value b. by reference c. element by element d. Any 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 Q7. An uninitialized pointer is known as: a. dangling pointer b. NULL pointer c. generic pointer d. None of the above 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 Q9. The arithmetic operation performed on pointer variables: a. multiplication of an integer with pointer b. addition of two pointers c. subtraction of two pointers d. addition of a float to a pointer Q10. Two ways to access elements of an array are: a. by value and by reference b. indexed and pointer notation Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 2. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 2 of 83 c. sequential and random d. none of the above Q11. The functions used for dynamic memory allocation are: a. delete and free b. free and realloc c. malloc and free d. malloc and calloc Q12. An array can be categorized as which type of data-structure: a. dynamic b. static c. int/char/float d. multi-dimensional Q13. The function used in C to de-allocate a memory block is: a. delete b. free c. malloc d. realloc Q14. A collection of elements of different data-types is known as: a. array b. union c. structure d. linked list 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 Q17. A one-way list is called: a. circular linked list b. array c. queue d. single linked list Q18. An orphaned block is the result of: a. memory leak b. garbage collection c. free function d. all of the above Q19. A ____ pointer can point to any data-type: a. NULL pointer b. void pointer c. dangling pointer d. such a pointer does not exist 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
  • 3. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 3 of 83 c. Hard disk d. Heap Q23. A linked list is a linear collection of homogeneous elements called: a. structures b. nodes c. data d. none of the above Q24. Insertion in a linked list can be done from: a. beginning b. end c. middle d. all of the above Q25. The traversal directions possible in a double-linked list are: a. forward b. backward c. forward and backward d. right Q26. A node in a double linked list comprises of: a: information field b: information field and next pointer c: information field, next d: information field, next pointer, previous pointer & previous pointer pointer and thread field 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 Q32. The insertion/deletion operations on a stack are respectively known as: a: insert and delete b: enter and exit c: push and pop d: none of the above Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 4. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 4 of 83 Q33. A stack could be implemented using: a. single and double b. single and circular c: array and linked list d: any of the above 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 Q35. Postfix notation is also know as: a: polish notation b: reverse polish notation c: post notation d: post-operator notation Q36. A linked list is which type of data-structure: a: static b: non-linear c: linear d: none of the above Q37. Prefix notation is also known as: a: polish notation b: reverse polish notation c: pre notation d: post-operator notation 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 Q41. The condition top=-1 indicates that: a: stack has only one element b: stack is full c: stack is empty d: none of these Q42. The validity of an expression containing nested parentheses could be checked using: a: linked list b: queue c: tree d: stack Q43. A string could be reversed using the data-structure: 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
  • 5. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 5 of 83 Q45. In a normal queue, the underflow situation occurs when: a: rear=max -1 b: front= -1 c: rear=front d: rear=size-1 Q46. In a circular queue, one of the situations when overflow occurs: a: rear=size-1 b: rear=front c: (rear+1)=front d: front=-1 Q47. In postfix expression, the operator is placed: a: in-between the operands b: after the operands c: before the operands d: none of these 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 Q54. A non-linear hierarchical type of data-structure: a: graph b: tree c: array d: deque Q55. All leaf nodes of a tree are termed as: a: terminal nodes b: non-terminal nodes c: child nodes d: internal nodes Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 6. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 6 of 83 Q56. The root node is a: terminal node b: internal nodes c: child node d: none of the above Q57. The nodes belonging to the same parent are known as: a: descendants b: external nodes c: child nodes d: siblings Q58. A tree in which the degree of each node is either 0 or 2: a: complete binary tree b: binary search tree c: strictly binary tree d: none of the above 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: * Q62. In inorder traversal of a binary tree, the root node is visited: a: after the traversal of b: before the traversal of right & left subtrees right and left subtrees c. in-between the traversal of d: none of these left and right subtrees Q63. The height of the following binary tree is: a: 3 b: 4 c: 5 d: 2 Q64. A binary search tree is also known as: a: B-tree b: binary sorted tree c. binary ordered tree d: B+ tree Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 A B C D E F G
  • 7. 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 Q68. The complexity of bubble-sort algorithm is: a: O(n2 ) b: O(n) c: O(log n) d: O(n log n) Q69. Binary search is more suitable for: a: array b: linked list c: stack d: any of the above Q70. The complexity of binary-search algorithm is: a: O(log n) b: O(n log n) c: O(n) d: O(n2 ) Q71. The calloc() function can be used to allocate: a: multiple blocks of memory b: single block of memory c: two blocks of memory d: none of these Q72. The postfix expression of the infix expression: A+B*(C+D)/F+D*E is: a: AB+CD+*F/D+E* b: ABCD+*F/+DE*+ c: A*B+CD/F*DE++ d: A+*BCD/F*DE++ 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 Q74. Which data-structure is needed to convert infix notation to postfix notation: a: queue b: stack c: tree d: linked list Q75. Which of the following sorting procedures is the slowest: a: Quick sort b: bubble sort c: Shell sort d: insertion sort Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 8. 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 Q77. If n elements are to be sorted, the complexity of selection-sort is: a: O(1) b: O(log n) c: O(n) d: O(n2 ) Q78. The operation of processing each element in the list is known as: a: sorting b: merging c: inserting d: traversal Q79. Arrays are best data structures: a: for relatively permanent collections b: when the size of structure is constantly changing c: for both the above situations d: for none of the above situations 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 Q81. Pick the odd one out: a: insertion sort b: selection sort c: counting sort d: merge sort 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 Q85. The searching technique suitable for unsorted arrays: a: binary search b: linear search c: any of these d: none of these 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
  • 9. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 9 of 83 a: Big O notation b: Polish notation c: Time notation d: space complexity Q87. The technique of collecting unused memory is known as: a: garbage collection b: Dynamic memory allocation c: static memory allocation d: none of these 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 Q90. The main measures for the efficiency of an algorithm are: a: processor and memory b: complexity and capacity c: time and space d: data and space Q91. Which of the following cases does not exist in complexity theory: a: best case b: worst case c: average case d: Null case Q92. The worst case occurs in linear search algorithm when: a: item is in the middle of the b: item is not in the array array c: item is the last element in the d: item is the last element in the array array or not in the array at-all Q93. The complexity of merge sort algorithm is: a: O(n) b: O(log n) c: O(n2 ) d: O(n log n) Q94. The complexity of linear search algorithm is: a: O(n) b: O(log n) c: O(n2 ) d: O(n log n) 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 Q96. Linked lists are best suited: a: for relatively permanent collections b: when the size of structure is constantly changing c: for both the above situations d: for none of the above situations Q97. The memory address of the first element of an array is called: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 10. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 10 of 83 a: floor address b: foundation address c: first address d: base address 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 Q99. Which of the following data-structures are indexed structures: a: linear arrays b: linked lists c: both of the above 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 Q102. Which of the following statements is false: a: Arrays are static data structures b: data elements in linked list need not be stored in adjacent space in memory c: pointer stores the next data element d: linked lists are collection of nodes of a list that contain information part & next pointer Q103. Which of the following is a two-way list: a: grounded header list b: circular header list c: linked list with header & trailer nodes d: none of the above Q104. The terms “push” and “pop” are related to: a: array b: lists c: stacks d: all of the above Q105. The depth of a complete binary tree is given by: a: n log n b: n log n +1 c: log n d: log n +1 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
  • 11. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 11 of 83 Q107. An algorithm that calls itself directly or indirectly is known as: a: sub-algorithm b: recursive algorithm c: polish notation d: traversal algorithm 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 Q109. Value of first linked list index is: a: 1 b: 0 c: -1 d: none of these 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 Q112. In a heap tree: a: value in a node is greater than every b: value in a node is greater than value in left subtree and smaller than the value of its child nodes right subtree c: both the above conditions d: none of the above conditions 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 Q115. Which of the following algorithms is of divide and conquer type: a: bubble-sort b: insertion sort c: quick sort d: all of the above Q116. One of the applications of a linked list: a: Polynomial evaluation b: Postfix expression evaluation c: determining the distance traveled d: none of these Q117. A tree having any number of nodes: a: binary tree b: general tree c: B-tree d: AVL tree Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 12. 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 Q120. Heaps are of two types: a: high and low b: max and min c: B and B+ d: none of the above Q121. Incase of min-heap, the value present in any node is: a: greater than all its children b: smaller than all its children c: equal to all its children d: greater than values in left subtree and smaller than values in right subtree Q122. A min-heap is also known as: a: decreasing heap b: descending heap c: low heap d: none of these Q123. A max-heap is also known as: a: increasing heap b: ascending heap c: high heap d: none of these 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 Q125. A matrix which has most of its values equal to 0: a: sparse matrix b: zero-matrix c: empty matrix d: none of the above Q126. A sparse matrix can also be represented using: a: queue b: stack c: tree d: linked list Q127. A B-tree grows at the: a: root b: leaves c: braches d: any of the above Q128. A binary tree grows at the a: root b: leaves c: braches d: any of the above Q129. Shell sort is an improvisation over: a: quick- sort b: merge-sort Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 13. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 13 of 83 c: insertion-sort d: none of these 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 Q131. While calculating time-complexity, the program-time which is considered is: a: compile time b: execution time c: both compile and run-time d: none of the above Q132. The time complexity of the following algorithm is: sum(a,n){ s=0; for i= 1 to n{s=s+a[i]; } return s;} a: 3n+2 b: 2n +3 c: n+1 d: 2n+2 Q133. Complexity of heap sort a: O(n) b: O(log n) c: O(n2 ) d: O(n log n) 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 Q135. The leaf nodes of a tree have height equal to: a: height of the tree b: zero c: one d: none of these 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 Q137. Height of a full binary tree with n internal nodes is: a: n log n b: n c: n+1 d: log n Q138. The degree of a leaf node is: a: 1 b: 0 c: -1 d:2 Q139. A right in-threaded binary tree contains: a: inorder successor b: inorder predecessor c: NULL d: preorder successor 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
  • 14. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 14 of 83 a: First fit b: Best fit c: Worst fit d: Next fit Answers 1(d) 2(b) 3(c) 4(b) 5(a) 6(a) 7(a) 8(c) 9(c) 10(b) 11(d) 12(b) 13(b) 14(c) 15(b) 16(c) 17(d) 18(a) 19(b) 20(b) 21(c) 22(d) 23(b) 24(d) 25(c) 26(c) 27(d) 28(d) 29(c) 30(c) 31(b) 32(c) 33(c) 34(d) 35(b) 36(c) 37(a) 38(c) 39(d) 40(a) 41(c) 42(d) 43(d) 44(a) 45(b) 46(c) 47(b) 48(a) 49(a) 50(a) 51(b) 52(c) 53(a) 54(b) 55(a) 56(b) 57(d) 58(c) 59(a) 60(a) 61(a) 62(c) 63(a) 64(b) 65(b) 66(a) 67(c) 68(a) 69(a) 70(a) 71(a) 72(b) 73(a) 74(b) 75(b) 76(d) 77(d) 78(d) 79(a) 80(a) 81(c) 82(b) 83(a) 84(b) 85(b) 86(a) 87(a) 88(a) 89(a) 90(c) 91(d) 92(d) 93(d) 94(a) 95(d) 96(b) 97(d) 98(a) 99(a) 100(c) 101(a) 102(c) 103(d) 104(c) 105(d) 106(a) 107(b) 108(b) 109(b) 110(a) 111(c) 112(b) 113(d) 114(c) 115(c) 116(a) 117(b) 118(a) 119(c) 120(b) 121(b) 122(b) 123(b) 124(a) 125(a) 126(d) 127(a) 128(b) 129(c) 130(b) 131(b) 132(b) 133(d) 134(b) 135(b) 136(b) 137(d) 138(b) 139(a) 140(a) 141(b) 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
  • 15. 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 n0 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 2. Write a program to merge two sorted arrays. Ans: The program to merge two sorted arrays is as follows: #include<stdio.h> #include<conio.h> void main() { int a[5]={10,20,30,40,50},b[5]={11,22,28,30,35},c[10],i,j,k; for(i=0,j=0,k=0;i<=4 && j<=4;k++) {if(a[i]<=b[j]) {c[k]=a[i]; i++; } else { c[k]=b[j]; j++; } } while(i<=4) { c[k]=a[i]; i++; k++; } while(j<=4) { c[k]=b[j]; j++; k++; } clrscr(); for(k=0;k<=9;k++) Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 16. 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. Different operations possible on pointer variables are: 1) Addition of an integer to a pointer 2) Subtraction of an integer from a pointer 3) Subtraction of two pointers 4) Comparison of two pointers 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. 4. Explain what is meant by an array of pointers with the help of an example. Ans: A pointer is a variable that contains the address of another variable. i.e. it points to another variable. A pointer array or an array of pointers is a collection of pointer variables where each pointer variable points to a specific memory location. The pointer variables are stored in continuous memory locations. The size of this array is fixed at compile time. It is declared in the same way as other arrays are declared except an asterik(*) is specified before the array name. For eg. int *ptr[3]; here ptr is an array of pointers that can store the addresses of 3 memory locations. The array is organized in the memory as 0 1 2 ptr Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 17. 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’. 5. Write a program to find the product of two matrices. Ans: The program for multiplication of two matrices is as follows: #include<stdio.h> #include<conio.h> void main() { int a[3][3],b[3][3],c[3][3],i,j,k; clrscr(); 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(k=0;k<3;k++) { c[i][k]=0; for(j=0;j<3;j++) c[i][k]=c[i][k]+a[i][ j ]*b[ j ][k]; } } Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 18. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 18 of 83 printf (“Result of Multiplicationn”); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf(“%d”,c[i][j]); } printf(“n”); } getch(); } 6. Write a program to add two matrices. Ans: The program for addition of two matrices is as follows: #include<stdio.h> #include<conio.h> void main() { 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(); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 19. 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 elementsn"); 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=%dn",sa); printf("Sum of elements below the main diagonal=%dn",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. The algorithm for it, is as given below: Reverse(start) 1. temp=start 2. ptr=NULL Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 20. 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> struct node{int info; struct node * next; struct node *back; }*start,*last,*nw,*ptr,*save; 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
  • 21. 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
  • 22. 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. 11. Define a structure. What is a self-referential structure? Explain with example. 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; }; 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 36 bytes, comprising of rno, name and marks in a sequential order. A self-referential structure is a structure which has atleast one member which is of the same type as the structure itself. It is different from an ordinary structure because it has atleast one structure pointer of its own type as one of its members. Self referential structures are needed in situations when the exact number of records to be input is not known. With the help of these structures, linked records can be created. Unlike arrays, linked records are stored in non-contiguous locations but are linked to each other with the help of pointers. For eg. a self-referential structure can be declared in the following way: struct student{ int rno; char name[30]; struct student *next; }; The above-mentioned structure declaration contains next pointer which is of the same type as the structure itself which is used to point to a record of the same type. 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
  • 23. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 23 of 83 ii. Set temp=temp->next 4. Return count 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. 14. Name the different types of linked list? Ans. The various types of linked list are:- 1. Single-linked list 2. Double-linked list 3. Circular linked list 4. Header linked list Single-linked list:> A linked list whose node contains two parts i.e. information part & link part & null value in the link part signifies last node. As it has a single link which is to the next node, it is known as single linked list. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 24. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 24 of 83 Info Link 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 Q15. Write the algorithm for reversing a string using a stack. Ans: The algorithm for reversing string using a stack is as follows: Reversal(top,str) 1. Set I=0 2. while(I<length_of_str) a. Push str[I] onto the stack b. Set I=I+1 3. Set I=0 4. while(top != NULL) a. Pop the top element of the stack and store it in str[I] b. Set I=I+1 5. Print “The reversed string is “ ,str 6. Exit Q16. Write the algorithm for checking the validity of parentheses. Which data-structure is used for this purpose. Ans: A stack is used for the purpose of checking the validity of parentheses. The algorithm for checking the validity of parentheses is as follows: 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 Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 25. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 25 of 83 b. Else If (expr[I]=’)’ or expr[I]=’}’ or expr[I] =’]’) i. if(top=NULL) 1. Display “invalid expression” 2. Exit ii. else 1. Pop the top symbol from the stack and store it in c 2. if(c and expr[I] are not matching symbols) a. Display “Invalid expression” b. Exit c. Set I=I+1 3. if(top != NULL) a. Display “ Invalid epression” 4. else a. Display “Valid expression” 5. Exit Q17. Write the algorithm for evaluation of a postfix expression. Ans: 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 in P until the ‘)’ is encountered. 3. If an operand is encountered, then: a. 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. Push the result of (b) back onto the STACK 5. Set VALUE equal to the top element of STACK 6. Exit. Q18. Convert the following expression from a.) infix to postfix and b.) infix to prefix A * (B+C) ↑ D-E / (F+G) Ans: a) infix to postfix A * (B+C) ↑ D-E / (F+G) A*BC+ ↑ D-E /FG+ A*BC+D↑ - E / FG+ ABC+D↑* -E/FG+ ABC +D↑* - EFG+/ ABC+D↑*EFG+/- (Postfix expression) b) infix to prefix A * (B+C) ↑ D-E / (F+G) A* +BC ↑ D-E / +FG A* ↑+BCD –E/ +FG Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 26. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 26 of 83 *A↑+BCD – E / +FG *A↑+BCD - /E+FG -*A↑+BCD /E+FG (Prefix expression) Q19. Differentiate between infix, postfix and prefix expressions Ans: The general arithmetic expression is written in infix notation, containing parentheses.Because of the precedence of operators, it involves a back and forth movement, making the evaluation difficult and time- consuming. Therefore these expressions are converted into another notation, the evaluation of which is easier and faster. A Polish mathematician named Jan Lukasiewicz suggested two alternative notations to represent an arithmetic expression. The notation in which the operator occurs before the operands is known as Prefix notation(also known as Polish Notation). The notation in which the operator occurs after the operands is known as Postfix notation(also known as Reverse Polish Notation). In these notations, the operations are performed in the order in which the operators are encountered in the expression. These expressions do not contain parentheses and while evaluating them, the precedence of operators is insignificant. As a result they are computed faster than infix expressions. Eg. of Infix expression: A * (B+C) ↑ D-E / (F+G) When converted to postfix: ABC+D↑*EFG+/- When converted to prefix: -*A↑+BCD /E+FG Q20. Consider the following stack of size 5. Top=2. Stack: Delhi, Kolkatta, Patiala. Describe the stack when the following operations take place: a. Chandigarh is pushed b. Ahmedabad is pushed c. Pop the element d. Chennai is pushed e. Lucknow is pushed f. Pop the element Ans: a: When operation a is performed, top becomes equal to 3 and Chandigarh is pushed onto the top of the stack: Stack: Delhi, Kolkatta, Patiala, Chandigarh 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: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 27. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 27 of 83 Stack: Delhi, Kolkatta, Patiala, Chandigarh, Chennai 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) Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 28. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 28 of 83 1. Set temp=start, prev =start 2. Allocate memory to nptr 3. If nptr=NULL 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. Q24. Define a queue. Specify some of the applications of a queue. 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. Eg. - There are numerous examples of queues in our everyday life e.g. people waiting in a line at a bank, form a queue. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 29. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 29 of 83 Typical uses of queues are in simulations and operating systems. • 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 2. No. of elements=As rear<front: (rear+1)+(upper subscript-front +1) = (4+1)+ (9-9+1)= 5+1=6 3. No. of elements = As rear > front: rear-front+1=5-4+1=2 After two elements are deleted : no. of elements=2-2=0 Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 30. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 30 of 83 Q27. Consider the following circular queue of size 5. front=0,rear=2. Circular queue: Delhi, Kolkatta, Patiala. Describe the queue when the following operations take place: a. Chandigarh is inserted b. Ahmedabad is inserted c. An element is deleted d. Chennai is inserted e. Lucknow is inserted f. An element is deleted 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. Ans: For a normal 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
  • 31. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 31 of 83 For a circular queue: 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
  • 32. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 32 of 83 i. If item < ptr->info 1. Call insert_node(item, ptr->left) ii. Else 1. Call insert_node(item, ptr->right) 3. Exit 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
  • 33. 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
  • 34. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 34 of 83 Left and right pre-threaded For representing a threaded binary tree in memory, the node contains like a normal binary tree, the fields: information, right pointer and left pointer. However, in a threaded binary tree, the right/left pointers might contain the addresses of right/left child nodes but if they are NULL, may respectively contain the inorder successor’s address or inorder predecessor’s address. To specify whether, right/left pointer is containing a child node address or successor/predecessor address, a one-bit thread field is used containing a one in the latter case. The node representation of an right-in-threaded binary tree is as shown below: right pointer information left thread pointer Q35. Create a binary search tree for the following sequence of elements. 81,61,52,90,87,88 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. Creating a Binary search for the sequence of elements given: When 81 is inserted, it being the first element, becomes the root node: When 61 is inserted, as it is smaller than 81, it is put onto the left of 81: When 52 is inserted , it being smaller than 81 and 61, is inserted to the left of 61: When 90 is inserted, it being greater than 81, is inserted to the right of 81: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 8 1 8 1 6 1 81 6 1 5 2 8 1 6 1 5 2 9 0
  • 35. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 35 of 83 When 87 is inserted, it being greater 81 and less than 90, it should be inserted to the left of 90: 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 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; }; For eg. following is the linked list representation of a binary tree: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 8 1 6 1 5 2 9 0 8 7 8 1 6 1 5 2 9 0 8 7 8 8 A B C D E F
  • 36. 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: info left right 1 C -1 2 2 F -1 -1 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: Q38. Define sorting. Differentiate between internal and external sorting. Ans: The process of arranging data in some logical order is known as sorting. The order can be ascending/descending for numeric data and alphabetical for character data. There are two types of sorting namely internal sorting and external sorting. If all the data to be sorted fits entirely in the main memory , then internal sorting is used. There are different kinds of internal sorting which are used viz. selection sort, bubble sort, insertion sort, etc. The choice of a particular algorithm depends upon the properties of data and operations to be performed on the data. If all the data to be sorted does not fit entirely in the main memory, external sorting is used. It requires the use of external memory such as disks, tapes, during sorting. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 Root A B D C E F G H
  • 37. 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. Q39. Write the program for performing binary search. Ans : The program for performing binary search is as follows: #include<stdio.h> #include<conio.h> void bin_search(int[],int,int ); void main() {int a[10]={10,21,33,54,67,88,97,101,112,120}; int n; clrscr(); printf("Enter the no. to be searched "); scanf("%d",&n); bin_search(a,10,n); getch(); } void bin_search(int a[],int size,int n) {int mid,beg=0,end=size-1; while(beg<=end) {mid=(beg+end)/2; if(n==a[mid]) {printf("Element found at position %d",mid+1); getch(); return; } else if(n >a[mid]) beg=mid+1; else end=mid-1; } if(beg>end) printf("No. not found "); return; } 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: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 4 4 20 2 9 0 5 5 4 9 0 4 4 9 0 4 4 5 5 20 2 9 0 20 2 5 5 4 4
  • 38. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 38 of 83 Max-heap Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 20 2 9 0 5 5 4 4 62 0 202 62 0 5 5 4 4 9 0- 62 0 20 2 5 5 4 4 9 0 62 0 20 2 5 5 4 4 9 0 5 1 1 7 62 0 20 2 5 5 4 4 9 0 5 1 62 0 20 2 5 5 4 4 9 0 5 1 1 7 5 6 20 2 5 5 5 6 9 0 5 1 1 7 4 4 620
  • 39. 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: i) Arrays- An array is defined as a collection of elements of the same data-type , stored in continuous memory locations referred by a single name. The size of the array has to be specified at the time of writing the program and memory for it is reserved at compile-time. Hence it is a static data-structure. Arrays are of two types: one-dimensional and multi-dimensional. Multi-dimensional arrays could be : two-dimensional, three-dimensional and so-on. Each element of the array is referred using a subscript or index. Insertion/Deletion in an array can take place from the beginning, middle or end. j) Linked lists- It is a dynamic data-structure in which memory for each node is allocated at run-time from the heap portion of RAM. The memory allocation for the nodes need not be continuous as in arrays. It can be defined as a list of nodes where each node contains the information part and the address of the next node. Insertion/Deletion can take place from the beginning, middle or end. A linked list helps in better memory utilization. Linked lists could be: single, double or circular. k) Queues- It is a linear data-structure in which insertion can take place only at the end i.e. rear and deletion can take place only in the beginning i.e. front. As the element which is first in, is first out, therefore a Queue is known as a FIFO data-structure. For eg. implementation of a queue for cinema-tickets. l) Stacks-This is a linear data-structure in which the insertion/ deletion takes place only at one end which is the TOP. The insertion operation is known as PUSH and deletion operation is known as POP. Since the element which is pushed last, is popped out first, a stack is known as a LIFO data-structure. b) Non-Linear data-structures- These data structures are not in a sequence. They are of the following two types: i)Trees- To represent a hierarchical structure, a tree is used. For eg. family tree, organization structure, etc. The node at the top which does not have a parent is called the root node. Every other node has a unique parent. The nodes with child nodes are called internal nodes and the nodes without children are called leaves or external nodes. j)Graphs- It is used to represent a non-sequential, non-hierarchical structure. A graph can be defined as a non-empty set of vertices and edges. For eg. an application needing to find the route between two cities will need to use a graph. Some operations which are performed on data-structures are: 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
  • 40. 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. Q2. Write short-notes on the following: a: Arrays b: Linked lists c: Trees d: Graphs Ans: a. Arrays- An array is defined as a collection of elements of the same data-type, stored in continuous memory locations referred by a single name. The size of the array has to be specified at the time of writing the program and memory for it is reserved at compile-time. Hence it is a static data-structure. Arrays are of two types: one-dimensional and multi-dimensional. Multi-dimensional arrays could be : two-dimensional, three- dimensional and so-on. Each element of the array is referred using a subscript or index. Insertion/Deletion in an array can take place from the beginning, middle or end. b: Linked lists- It is a dynamic data-structure in which memory for each node is allocated at run-time from the heap portion of RAM. The memory allocation for the nodes need not be continuous as in arrays. It can be defined as a list of nodes where each node contains the information part and the address of the next node. Insertion/Deletion can take place from the beginning, middle or end. A linked list helps in better memory utilization. Linked lists could be: single, double or circular. c. Trees- To represent a hierarchical structure, a tree is used. For eg. family tree, organization structure, etc. The node at the top which does not have a parent is called the root node. Every other node has a unique parent. The nodes with child nodes are called internal nodes and the nodes without children are called leaves or external nodes. d. Queues- It is a linear data-structure in which insertion can take place only at the end i.e. rear and deletion can take place only from the beginning i.e. front. Hence the element which is first in, is first out, therefore a Queue is known as a FIFO data-structure. For eg. implementation of a queue for cinema-tickets. 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}; An array can also be declared without size-specification if it is initialized: For eg: int a[]={10,20,30,40,50};/* Here the compiler will reserve memory for 5 elements as 5 element-values have been given.*/ Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 41. 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. When the array is stored row by row, it is known as row-major form. W hen the array is stored col by col, it is known as 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. Disadvantages of an array: An array has the following disadvantages: a: 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. b: For arrays, static memory allocation is used. This might result in a shortage of memory or memory may be wasted. Thus memory may not be properly utilized. c: Insertion and deletion of elements in an array requires a shifting of elements, thus is time-consuming. 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
  • 42. 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; } The program for deletion of an element from an array is as follows: #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
  • 43. 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
  • 44. 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) { Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 45. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 45 of 83 a=a+1; b=b+1; 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 detailsn"); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 46. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 46 of 83 for(i=0;i<=4;i++) {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("%dn",s[i].rno); printf("Name "); printf("%sn",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)); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 47. 10 20 30 40 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 47 of 83 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. 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 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. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 2 1 5 0start
  • 48. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 48 of 83 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. 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); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 49. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 49 of 83 } nptr=malloc(sizeof (struct node)); printf("enter value"); 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; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 50. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 50 of 83 struct node*ptr=st; if(ptr==NULL) return 0; else {while(ptr!=NULL) {c++; ptr=ptr->next; } return c; } } The operations which can be performed on it are: • 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’) Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 51. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 51 of 83 { printf(“Enter value to be inserted” scanf(“%d”,&item); fflush(stdin); 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 Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 52. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 52 of 83 b. nptr->info=n c. nptr->next=NULL d. if(start=NULL) 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. The algorithm for forward traversal of a double linked list is as follows: forward(start) 1. ptr=start 2. while(ptr !=NULL) a. Display ptr->info b. ptr=ptr->next 3. Exit The algorithm for backward traversal of a double linked list is as follows: backward(last) 1. ptr=last 2. while(ptr !=NULL) i. Display ptr->info ii. ptr=ptr->prev Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 53. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 53 of 83 3. Exit Q13. Write a program to implement doubly (two–way) linked list. Ans. The program showing the implementation of a double linked list is as follows: #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,i; 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++) { Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 54. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 54 of 83 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; } } } void display(struct node *q) { while(q!=NULL) { printf(“%dn”,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> Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100
  • 55. SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 55 of 83 #define max 10 int top=-1; int stack[max]; 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(“%dn”,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. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100