SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 1 of 82 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 [QUESTIONS 1 TO 141] 1 Marks Questions [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) c. sequential and random Page 2 of 82 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. a. . c. <- To access elements of a structure through a pointer , the operator used is: b. -> 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) c. Hard disk Page 3 of 82 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 82 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. a: 37 c: 40 The postfix expression: 5 6 2 + * 12 4 /- when evaluated gives the following result: b: -37 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 82 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) Q56. The root node is a: terminal node c: child node Page 6 of 82 b: internal nodes 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. tree: a: c: a What is the root node for the algebraic expression : a*(b+c)-d, if it is represented in the form of a b: + 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 B D F a: 3 c: 5 C E G b: 4 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 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 7 of 82 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. a: E c: F In the following post-order traversal of a binary tree: E,C,K,A,H,B,G,D,F, the root node is: b: H 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 82 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 constantly changing c: for both the above situations b: when the size of structure is 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 c: counting sort b: selection 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) a: Big O notation c: Time notation Page 9 of 82 b: Polish 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. a: F c: C The root node of a binary tree whose preorder traversal is: F,B,A,D,C,E,G, I, H is: b: H 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) 2 c: O(n ) 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 constantly changing c: for both the above situations Q97. b: when the size of structure is d: for none of the above situations 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) a: floor address c: first address Page 10 of 82 b: foundation 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 c: stacks b: lists 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 82 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. a: 1 c: -1 Value of first linked list index is: b: 0 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. a: short c: float Which of the following abstract data types is not used by integer abstract data type group? b: int d: long Q112. In a heap tree: a: value in a node is greater than every value in left subtree and smaller than right subtree c: both the above conditions b: value in a node is greater than the value of its child nodes 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 c: determining the distance traveled b: Postfix expression evaluation d: none of these Q117. A tree having any number of nodes: a: binary tree c: B-tree d: AVL tree b: general tree Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 12 of 82 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 c: B and B+ b: max and min 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 c: high heap b: ascending 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 c: braches b: leaves d: any of the above Q128. A binary tree grows at the a: root c: braches b: leaves 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) c: insertion-sort Page 13 of 82 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) c: O(n2) b: O(log n) 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 c: -1 b: 0 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) a: First fit c: Worst fit Page 14 of 82 b: Best fit d: Next fit Answers 1(d) 9(c) 17(d) 25(c) 33(c) 41(c) 49(a) 57(d) 65(b) 73(a) 81(c) 89(a) 97(d) 105(d) 113(d) 121(b) 129(c) 137(d) 2(b) 10(b) 18(a) 26(c) 34(d) 42(d) 50(a) 58(c) 66(a) 74(b) 82(b) 90(c) 98(a) 106(a) 114(c) 122(b) 130(b) 138(b) 3(c) 11(d) 19(b) 27(d) 35(b) 43(d) 51(b) 59(a) 67(c) 75(b) 83(a) 91(d) 99(a) 107(b) 115(c) 123(b) 131(b) 139(a) 4(b) 12(b) 20(b) 28(d) 36(c) 44(a) 52(c) 60(a) 68(a) 76(d) 84(b) 92(d) 100(c) 108(b) 116(a) 124(a) 132(b) 140(a) 5(a) 13(b) 21(c) 29(c) 37(a) 45(b) 53(a) 61(a) 69(a) 77(d) 85(b) 93(d) 101(a) 109(b) 117(b) 125(a) 133(d) 141(b) 6(a) 14(c) 22(d) 30(c) 38(c) 46(c) 54(b) 62(c) 70(a) 78(d) 86(a) 94(a) 102(c) 110(a) 118(a) 126(d) 134(b) 7(a) 15(b) 23(b) 31(b) 39(d) 47(b) 55(a) 63(a) 71(a) 79(a) 87(a) 95(d) 103(d) 111(c) 119(c) 127(a) 135(b) 8(c) 16(c) 24(d) 32(c) 40(a) 48(a) 56(b) 64(b) 72(b) 80(a) 88(a) 96(b) 104(c) 112(b) 120(b) 128(b) 136(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 spacecomplexity, 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 82 Algo Sum(a,n) { s=0; For i=1 to n {s=s+a[i]; } return s; } Its time complexity= no. of program steps=2n+3 and space complexity >= n+3 Big-O notation or Asymptotic notation- The Big O notation provides a theoretical measure of the time or memory required by an algorithm. It also enables the user to compare the expected run times. It calculates the order of the equation required to maintain the complexity of the algorithm. The function f(n)= O(g(n)) if and only if there exist positive constants c and n 0 such that f(n)<=c*g(n) for all n, n>=n0 For eg: 3n+2 = O(n) as 3n+2 <=4n for all n>=2 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 82 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 memoryblocks. 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 82 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 82 printf (“Result of Multiplication\n”); 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 82 } 7. Write a program to find the sum of elements below the main diagonal and the sum of elements above the main diagonal of a matrix. Ans: Program to find the sum of elements above and below the main diagonal is as follows: #include<stdio.h> #include<conio.h> void main() {int a[3][3],i, j, sa=0, sb=0; clrscr(); printf("Enter array elements\n"); for(i=0;i<=2;i++) for(j=0;j<=2;j++) scanf("%d",&a[i][j]); for(i=0;i<=2;i++) {for(j=0;j<=2;j++) printf("%d ",a[i][j]); printf("\n"); } for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { if(j>i) sa+=a[i][j]; else if(j<i) sb+=a[i][j]; } } printf("Sum of elements above the main diagonal=%d\n",sa); printf("Sum of elements below the main diagonal=%d\n",sb); getch(); } 8. What is meant by reversing a linked list.? Write the algorithm for reversing. Ans: Reversing a linked list is the process of reversing the order of the linked list. After reversing the linked list, the first element becomes the last, the last becomes the first and so on. The resultant list after the reversing process is called the reversed linked list. This is done using 3 pointers: save, ptr and temp. Initially temp points to start and both ptr and save point to NULL. While traversing the list, temp points to the current node,ptr points to the node previously pointed to by temp and save points to the node previously pointed to by ptr. The links between the nodes are reversed by making the next field of the node pointed to by ptr to point to the last node and save point to the second last node of the list. Start is made to point to the node pointed to by ptr in order to make the last node as the first node of the list. 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) 3. 4. a. b. c. d. 5. 6. Page 20 of 82 save=NULL while(temp != NULL) save=ptr ptr=temp temp=temp->next ptr->next=save start=ptr 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 82 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 82 }; 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) ii. 4. Page 23 of 82 Set temp=temp->next 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. Info Link Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 24 of 82 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 b. Else If (expr[I]=’)’ or expr[I]=’}’ or expr[I] =’]’) i. if(top=NULL) Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Display “invalid expression” Exit 1. 2. ii. Page 25 of 82 else 1. 2. a. b. c. 3. a. 4. a. 5. Pop the top symbol from the stack and store it in c if(c and expr[I] are not matching symbols) Display “Invalid expression” Exit Set I=I+1 if(top != NULL) Display “ Invalid epression” else Display “Valid expression” 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 *A+BCD – 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 82 -*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 timeconsuming. 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: Stack: Delhi, Kolkatta, Patiala, Chandigarh, Chennai Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 27 of 82 f: When operation f is performed, top becomes equal to 3 and Chennai is popped from the stack: Stack: Delhi, Kolkatta, Patiala, Chandigarh Q21. Evaluate the following postfix expression using algorithm and show the contents of the stack after the execution of each operation: 20,30,+,50,40,-,* Ans: The algorithm for postfix expression evaluation is as follows: a. Add a right parenthesis ‘)’ at the end of P. b. Scan P from left to right and repeat steps 3 & 4 for each element P until the ‘)’ is encountered. c. If an operand is encountered, then: a. Push it into STACK d. If an operator Ø is encountered, then: a. Remove the two top elements of STACK, where A is the top element and B is next-to top element. b. Evaluate B Ø A c. Push the result of (b) back onto the STACK e. Set VALUE equal to the top element of STACK f. Exit Now evaluating the given postfix expression: . When 20 is encountered, since it is an operand , it is pushed onto the stack: Stack: 20 When 30 is encountered, since it is an operand , it is also pushed onto the stack: Stack:20,30 When + is encountered , since it is an operator, two elements are popped out of the stack: So, A becomes=30 and B becomes= 20 Now, B+A is performed, making the result=50 which is pushed onto the stack. Stack: 50 When 50 is encountered, since it is an operand , it is pushed onto the stack: Stack:50,50 When 40 is encountered, since it is an operand , it is pushed onto the stack: Stack:50,50,40 When - is encountered , since it is an operator, two elements are popped out of the stack: So, A becomes=40 and B becomes= 50 Now, B-A is performed, making the result=10 which is pushed onto the stack. Stack: 50,10 When * is encountered , since it is an operator, two elements are popped out of the stack: So, A becomes=10 and B becomes= 50 Now, B*A is performed, making the result=500 which is pushed onto the stack. Stack: 500 As the end of the string is encountered, the topmost element is popped out of the stack and Value becomes =500 which is the result. Q22. What is a priority queue? Explain. Write the algorithm for insertion in a priority queue. Ans: It is a data-structure in which each element is assigned a priority and the elements are added or removed according to that priority. While implementing a priority queue, the following two rules are applied: a) The element with the highest priority is processed before any element of lower priority. b) The elements with the same priority are processed according to the order in which they are added to the queue. The algorithm for insertion into a priority queue: qinsert(start) 1. 2. Set temp=start, prev =start Allocate memory to nptr Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) 3. a. b. 4. 5. 6. 7. 8. a. b. 9. a. i. 1. 2. ii. 1. 2. b. i. 10. Page 28 of 82 If nptr=NULL Print “Overflow” Exit Read item, prno Set nptr->info=item Set nptr->prno =prno Set nptr->next=NULL If (start=NULL or start->prno > prno) start =nptr start->next=temp else while(temp!=NULL) if(temp->prno > prno) prev->next=nptr nptr->next=temp else Set prev=temp temp=temp->next if(temp=NULL) Set prev->next=nptr 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, parenthesesvalidity 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. Typical uses of queues are in simulations and operating systems. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 29 of 82 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. 3. No. of elements=As rear<front: (rear+1)+(upper subscript-front +1) = (4+1)+ (9-9+1)= 5+1=6 No. of elements = As rear > front: rear-front+1=5-4+1=2 After two elements are deleted : no. of elements=2-2=0 Q27. Consider the following circular queue of size 5. front=0,rear=2. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 30 of 82 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 82 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 reestablished 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) i. Page 32 of 82 If item < ptr->info Call insert_node(item, ptr->left) Else Call insert_node(item, ptr->right) Exit 1. ii. 1. 3. 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 82 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 nonroot 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: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 34 of 82 Left and right in-threaded 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 Q35. information left thread pointer 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: 81 When 61 is inserted, as it is smaller than 81, it is put onto the left of 81: 81 61 When 52 is inserted , it being smaller than 81 and 61, is inserted to the left of 61: 81 61 52 When 90 is inserted, it being greater than 81, is inserted to the right of 81: 81 61 90 Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. 52 Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 35 of 82 When 87 is inserted, it being greater 81 and less than 90, it should be inserted to the left of 90: 81 90 61 87 52 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 81 90 61 87 52 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: A B D C E F Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 36 of 82 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 Root left 1 C -1 2 2 F -1 -1 3 A 4 1 4 B 5 6 5 D -1 -1 6 E -1 -1 right Q37. Generate a binary search tree with 11 nodes whose inorder and postorder traversal is as follows: Inorder: D B A E C G F H Postorder: D B E G H F C A Ans: As, in the post-order traversal, the last node traversed is the root-node, the root-node for the tree to be constructed is A. Further from the given inorder traversal, it can be made out that the nodes D and B are to the left of node A and the nodes E, C,G,F,H are to the right of node A. The tree with the above-mentioned inorder and post-order traversals is as shown below: A C B D F E G H 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 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 37 of 82 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: 44 90 44 90 90 202 Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. 44 202 55 Ph. 0175-2205100, 55 2215100 90 55 202 44 44 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) 202 202 55 90 44 Page 38 of 82 620 44 620 620 55 202 90 - 44 90 620 202 44 620 55 90 55 202 44 51 55 90 620 17 51 Max-heap 620 202 44 56 55 202 55 90 51 17 56 90 51 17 44 Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 39 of 82 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. one by one. Traversing- This refers to accessing all the data elements in the data-structure Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 40 of 82 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, threedimensional 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 82 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 multidimensional 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 82 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 82 { 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 82 Ans: Call by value method: Under this method of calling a function, the parameters are passed into a function by value. As the function has the limitation of returning back only a single value to the calling function, more than one changed values are not available in the calling function. Eg. of calling a function by value: void add(int,int); void main() { int x,y; x=10; y=20; add(x,y); } void add(int a , int b) { int c =a+b; } Call by reference:In this approach the addresses of the actual arguments are passed as parameters to the called function. In this way processing is done on the addresses of the variables, so any changes made in the called function are visible to the calling function. This method of calling a function is needed when more than one changed values in the called function have to be reflected back in the called function. For eg: #include<stdio.h> void add(int*,int*); void main() {int a,b; a=10; b=20; add(&a,&b); printf(“%d %d”,a,b); } void add(int *a, int *b) { *a=*a+1; *b=*b+1; } When more than one changed values of the parameters passed into a function have to be available in the calling function, the call by value method doesn’t do the needful, and call by reference method needs to be used. This is explained by the under-mentioned program: /* call by value */ void main() { int a=10; int b=20; add(a,b); printf(“a=%d”,a); printf(“b=%d”,b); } void add(int a, int b) { a=a+1; b=b+1; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 45 of 82 printf(“a is %d”,a); printf(“b is %d”,b); } Output: a=11 b=21 a=10 b=20 Here, the changed values of a and b in the function add are not available in main. /* call by reference */ void main() { int a=10; int b=20; add(&a,&b); printf(“a=%d”,a); printf(“b=%d”,b); } void add(int *a, int *b) { *a= *a+1; *b= *b+1; } Output: a=11 b=21 Here, the changed values of a and b in the function add are available in main. Q6. Write a program to implement a structure student with fields-roll number, name and marks in three subjects. The program reads the data for 5 students using array of structures. Reverse the list of students using array of pointers. Ans : The program is as follows: #include<stdio.h> #include<conio.h> struct student{ int rno; char name[20]; int marks[3]; }; void main() {struct student s[5],*p[5],*t; int i,j; clrscr(); printf("Enter details\n"); for(i=0;i<=4;i++) Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 46 of 82 {printf("Rno "); scanf("%d",&s[i].rno); fflush(stdin); printf("Name "); gets(s[i].name); fflush(stdin); for(j=0;j<=2;j++) { printf("Marks %d ",j+1); scanf("%d",&s[i].marks[j]); fflush(stdin); } } for(i=0;i<=4;i++) p[i]=&s[i]; for(i=0,j=4;i<2;i++,j--) { *t=*p[i]; *p[i]=*p[j]; *p[j]=*t; } for(i=0;i<=4;i++) {printf("\nRno "); printf("%d\n",s[i].rno); printf("Name "); printf("%s\n",s[i].name); for(j=0;j<=2;j++) { printf("\nMarks %d ",j+1); printf("%d ",s[i].marks[j]); } } getch(); } Q7. What is the difference between static and dynamic memory allocation?Explain with example. What is memory leak? Ans: Static memory allocation refers to memory allocation at compile-time. For example an array is allocated memory at compile time. That is, the size of the array can not be changed at run-time. Dynamic memory allocation means allocating memory at run time from the heap portion of RAM. At run-time, depending upon the user’s requirement, memory can be allocated, resulting in a better utilization of memory. The functions generally used for this are: malloc malloc requires one argument - the number of bytes to be allocated dynamically. If the memory allocation is successful, malloc returns a void pointer – this can be assigned to a pointer variable, which will store the address of the allocated memory. If memory allocation fails , malloc returns a NULL pointer. Example: int *ptr; ptr = malloc(sizeof(int)); calloc Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 47 of 82 calloc is similar to malloc, but the main difference is that the values stored in the allocated memory space is zero by default. With malloc, the allocated memory could have any value. calloc requires two arguments. The first is the number of blocks to be allocated memory for. The second is the size of each block. calloc is used to allocate multiple memory blocks. Like malloc, calloc returns a void pointer if the memory allocation was successful, else it returns a NULL pointer. int *ptr; ptr = calloc(3, sizeof(int)); realloc If the space allocated is not sufficient, reallocation of space is possible using this function free This function is used to de-allocate the memory block which is no longer needed. Static memory allocation is faster than dynamic. But in static memory allocation, memory may be wasted or there may be a shortage of memory. On the other hand, incase of dynamic memory utilization, only as much memory is allocated as is needed. Thus it results in better memory utilization. A memory leak occurs when memory is allocated using malloc() function and not released using free() function. This results in an orphaned block which is not referenced by anything. Memory leak arises due to the following reasons: a. Memory blocks allocated are not released even when not required. b. The free statement is bypassed at the time of execution of the particular function. c. The memory allocated by malloc function is stored in a pointer variable which was already pointing to another memory location. Q8. What is a single linked list? How is it implemented? What are its advantages over an array? Ans: Single linked list: It is a linked list which has a single link(pointer) which is the address of the next node. Memory representation of linked list 1. Array representation: This is done with the help of two parallel arrays. The first array stores the information part and the second array stores the address of the next node. info next start 40 30 0 1 10 5 20 2 In the diagram above, the pointer start contains the position of the first element in the linked list which is 3. At the position 3 of the array—next, the number 5 indicates the position of the next element. A 0 in the array, next, indicates the end of the linked list, i.e. there are no further elements. 2. Dynamic representaion: In this representation, nodes are created for the linked list at run-time using memory allocation function, malloc(). The nodes are created from the memory area known as heap. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 48 of 82 The representation of a node in the linked list is done using the following self-referential structure: struct node{ int info; struct node *next; }; Advantages of linked lists over arrays: 1. As memory allocation is done at run-time, using a linked-list, results in better memory utilization. This is because we end-up creating only as many nodes as required by the user. Neither there is a wastage of memory nor a shortage which might happen incase of arrays. 2. As in a linked list the nodes are not allocated continuous memory, again this results in better memory utilization. 3. Insertion/Deletion is simpler and less time consuming as this requires only the adjustment of some pointers. In an array, this process takes time as it requires a shifting of elements. Q9. Write a program to show insertion in a single linked list at a specific position. What are the operations that can be performed on it? Ans: The program for insertion in a single linked list at a specific position is as follows: #include<stdio.h> #include<conio.h> #include<alloc.h> #include<process.h> struct node { int info; struct node *next; }; int count(struct node*); void main() { int i,pos,n; struct node *start,*ptr,*nptr; char ch='y'; clrscr(); start=NULL; while(ch=='y') {printf("enter position"); scanf("%d",&pos); fflush(stdin); n=count(start); if(pos==0||pos>n+1) { printf("position incorrect "); getch(); exit(0); } nptr=malloc(sizeof (struct node)); printf("enter value"); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 49 of 82 scanf("%d",&nptr->info); fflush(stdin); nptr->next=NULL; if(start==NULL) start=nptr; else { if(pos==1) { nptr->next=start; start=nptr; } else { i=1; ptr=start; while(i<pos-1) { ptr=ptr->next; i++; } if(ptr->next==NULL) ptr->next=nptr; else { nptr->next=ptr->next; ptr->next=nptr; } } } printf("insert another node"); ch=getchar(); fflush(stdin); } ptr=start; //Display while(ptr!=NULL) { printf("%d",ptr->info); ptr=ptr->next; } getch(); } int count(struct node*st) {int c=0; struct node*ptr=st; if(ptr==NULL) return 0; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 50 of 82 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’) { printf(“Enter value to be inserted” scanf(“%d”,&item); fflush(stdin); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 51 of 82 insertbeg(item); printf(“Enter another node?”); ch=getchar( ); fflush(stdin); } printf(“\n Displaying….\n”); ptr=start; while(ptr!=NULL) {printf(“%d “,ptr->info); ptr=ptr->link; } getch( ); } void insertbeg(int item) { nw=malloc(sizeof(struct node)); if(nw==NULL) {printf(“Overflow “); getch(); exit(0); } nw->info=item; nw->link=NULL; if(start==NULL) start=nw; else { nw->link=start; start=nw; } } Q11. What is a circular linked list? How is it advantageous over a single linked list? Write an algorithm for insertion from the beginning of a circular linked list. Ans: A circular linked list is one in which the last node of the list rather than containing a NULL, contains the address of the starting node. Thus the last node points back to the start of the linked list. It is advantageous over a single linked list as reaching any node in the list, the entire list could be traversed. We can reach any of its predecessor nodes. This is because when we traverse a circular linked list starting with a particular node, we come back to the same node at the end. The process of creation of a node in a circular list is the same as in a single linked list The algorithm for insertion from the beginning of a circular linked list is as follows: insert_beg(start,n) a. nptr=malloc b. nptr->info=n c. nptr->next=NULL d. if(start=NULL) Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) a. b. e. a. b. start=nptr start->next=start else set ptr=start while ptr->next != start ptr=ptr->next nptr->next=start start=nptr ptr->next=start i. c. d. e. f. Page 52 of 82 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 3. Exit Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 53 of 82 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++) { current = current->next; if(current==NULL) { Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 54 of 82 printf(“Insufficient nodes”); return; } } current->prev->next = current->next; if(current->next!=NULL) current->next->prev = current->prev; item=current->data; free(current); return; } } } void display(struct node *q) { while(q!=NULL) { printf(“%d\n”,q->data); q=q->next; } } void main() { struct node *p; p=NULL; clrscr(); add(&p,33); add(&p,12); add(&p,9); display(p); getch(); del(&p,2); display(p); getch(); } Q14. Using array implementation of a stack, write a program showing push and pop operations. Ans: Stack is a linear data-structure, also known as a LIFO data-structure as the last item pushed onto the stack is the first one to be out. The insertion operation is known as push and deletion operation is known as pop. Both these operations take place from beginning in a stack. The program showing push and pop operations on a stack is as follows: #include<stdio.h> #include<conio.h> #define max 10 int top=-1; int stack[max]; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 55 of 82 void push(int x) { if(top==max-1) { printf(“Overflow”); exit(0); } top=top+1; stack[top]=x; } int pop() { int n; if(top==-1) { printf(“Underflow”); exit(0); } n=stack[top]; top=top-1; return n; } void display() { int i; for(i=top;I>=0;I--) { printf(“%d\n”,stack[i]); } } void main() { int n; push(3); push(56); push(12); display(); n=pop(); printf(“%d”,n); display(); getch(); } Q15. What are the applications of a stack? Explain any one of them with the help of a program. Ans: Stack is a linear data-structure, also known as a LIFO data-structure as the last item pushed onto the stack is the first one to be out. The insertion operation is known as push and deletion operation is known as pop. Both these operations take place from beginning in a stack. The applications of a stack are as follows : 1. Enabling recursion 2. Checking validity of the parentheses in an expression Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) 3. 4. 5. Page 56 of 82 Conversion of infix into postfix Evaluation of postfix expression Reversing of a string A stack is used to convert infix to post fix expression. The program for it, is as mentioned below: #include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> void main() { char ie[20]; char pe[20]; char s[20]; int i,t=0,k=0; clrscr(); printf(“enter infix expr “); scanf(“%s”,ie); printf(“\noriginal exp=%s”,ie); i=strlen(ie); ie[i]=’)’; i=0; s[t]=’(‘; while(t!=-1) { if(ie[i]==’+’||ie[i]==’-‘||ie[i]==’*’||ie[i]==’/’) { if(t==0) { t++; s[t]=ie[i]; } else { if(ie[i]==’*’||ie[i]==’/’) {while(s[t]==’*’||s[t]==’/’) {pe[k]=s[t]; k++; t--; } t++; s[t]=ie[i]; } else Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 57 of 82 { while(s[t]==’*’||s[t]==’/’||s[t]==’+’||s[t]==’-‘) { pe[k]=s[t]; k++; t--; } t++; s[t]=ie[i]; } } } else if(ie[i]==’(‘) { t++; s[t]=ie[i]; } else if(ie[i]==’)’) { while(s[t]!=’(‘) { pe[k]=s[t]; k++; t--; } t--; } else { pe[k]=ie[i]; k++; } i++; } pe[k]=’\0’; printf(“\n postfix exp=%s”, pe); getch(); } Q16. Show the conversion of the following expression from infix to postfix using an algorithm. A+(B*C-(D/E ↑ F) *G)*H Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 58 of 82 Ans: A stack is used to convert infix to postfix expression. The algorithm for it is as mentioned below: Convert(top, I, P) [ I is an infix expression and P is a postfix expression] 1. Add ‘)’ to the end of I and push ‘(‘ onto the stack 2. Repeat the steps 3 to 6 till the stack gets empty 3. If a ‘(‘ is encountered: i. Push it onto the stack 4. If an operand is encountered i. Add it to P 5. If an operator is encountered i. Pop from the stack each operator with higher or same precedence and add it to P ii. Push the operator onto the stack 6. If a ‘)’ is encountered i. Pop from the stack each operator and add it to P till ‘(‘ is encountered ii. Remove ‘(‘ 7. Exit 8. Using the above mentioned algorithm to convert the given infix expression to postfix: Sno 1. 2. 3. 4. 5. 6. 7. 8. 9. Sno 10. 11 12 13 14 15 16 17 18 19 20 Symbol scanned A + ( B * C ( D Symbol scanned / E ↑ F ) * G ) * H ) Stack Postfix Expression ( (+ (+( (+( (+(* (+(* (+((+( -( (+( -( Stack A A A AB AB ABC ABC* ABC* ABC*D Postfix Expression (+( -(/ (+( -(/ (+( -( /↑ (+( -(/ ↑ (+((+( - * (+( - * (+ (+* (+* ABC*D ABC*DE ABC*DE ABC*DEF ABC*DEF↑/ ABC*DEF↑/ ABC*DEF↑/G ABC*DEF↑/G*ABC*DEF↑/G*ABC*DEF↑/G*-H ABC*DEF↑/G*-H*+ Q17. Evaluate the following postfix expression using algorithm. 23+4*5/ Ans: The algorithm for postfix expression evaluation is as follows: a. Add a right parenthesis ‘)’ at the end of P. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 59 of 82 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 Evaluating the given postfix expression using the above-mentioned algorithm: 1. When 2 is encountered, it being an operand, it is pushed onto the stack Stack: 2 2. When 3 is encountered, it being an operand, it is also pushed onto the stack Stack: 2 ,3 3. When + is encountered, since it is an operator, two elements which are 3 and 2 are popped out. A=3 and B=2. B + A is performed and the result which is 5, is pushed onto the stack Stack: 5 4. When 4 is encountered, it being an operand, it is pushed onto the stack Stack: 5 ,4 5. When * is encountered, since it is an operator, two elements which are 4 and 5 are popped out. A=4 and B=5. B * A is performed and the result which is 20, is pushed onto the stack Stack: 20 6. When 5 is encountered, it being an operand, it is pushed onto the stack Stack: 20, 5 7. When / is encountered, since it is an operator, two elements which are 5 and 20 are popped out. A=5 and B=20. B / A is performed and the result which is 4, is pushed onto the stack Stack: 4 8. As the end of the expression is reached, the result which is 4, is popped out and displayed. Q18. Show the linked list implementation of a stack. 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 the beginning in a stack. A stack could be implemented using an array or a linked list. When the linked list implementation is used, for representing each node which is pushed onto the stack, the following self-referential structure is used: struct node{ int info; struct node *next; }; The pointer pointing to the top of the stack is called top. The program for the linked list implementation of a stack showing push, pop and display operations , is as shown below: #include<stdio.h> #include<conio.h> struct node { int data; struct node *link; }; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 60 of 82 void push(struct node **top,int num) { struct node *temp; temp=(struct node*)malloc(sizeof(struct node)); if(temp==NULL) { printf(“Overflow”); exit(); } temp->data=num; temp->link=*top; *top=temp; } void display(struct node *q) { while(q!=NULL) { printf(“%d\n”,q->data); q=q->link; } } int pop(struct node **top) { int item; struct node *temp; if(top==NULL) { printf(“Underflow”); exit(); } item=(*top)->data; *top=(*top)->link; free(temp); return item; } void main() { int n; struct node *p; clrscr(); p=NULL; push(&p,14); push(&p,23); push(&p,67); display(p); n=pop(&p); printf(“\nelement popped out is %d\n”,n); display(p); getch(); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 61 of 82 } The output of the above program would be as follows: 67 23 14 element popped out is 67 23 14 Q19. Write a program for the array-implementation of a queue. Ans: In the array-implementation of a queue, an array is considered to be a queue and insertion and deletion operations are performed. front is an integer variable which points to starting element and rear is an integer variable which points to the last element. The program showing the array implementation of a queue is as shown below: #include<stdio.h> #include<conio.h> #include<process.h> #define max 10 int front=-1; int rear=-1; int q[max]; void insertq(int x) { if(rear==max-1) { printf("Overflow"); exit(0); } if (front==-1) front=rear=0; else rear=rear+1; q[rear]=x; } void deleteq() { if(front==-1) { printf("Underflow"); exit(0); } if(front==rear) { front=-1; rear=-1; exit(0); } Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 62 of 82 front=front+1; } void display() { int i; for(i=front ;i<=rear;i++) { printf("%d ",q[i]); } } void main() { clrscr(); insertq(23); insertq(6); insertq(21); display(); deleteq(); printf("\nafter deletion \n"); display(); getch(); } The output of the above program is: 23 6 21 after deletion 6 21 Q20. Write an algorithm for the linked-list-implementation of a queue. Ans: In for the linked-list-implementation of a queue, each node has the information part and a pointer with the name next, pointing to the next node. front is a pointer pointing to the starting node and rear points to the last node. The insertion in a queue takes at the end and deletion from the beginning. The algorithms for insertion and deletion in a queue are mentioned below: qinsert(front,rear,item) 1. Allocate memory for nptr 2. if nptr=NULL a. Display “Overflow” b. Exit 3. Read item 4. nptr->info=item 5. nptr->next =NULL 6. if(front =NULL) a. rear=front=nptr 7. else a. rear->next=nptr b. rear=nptr 8. Exit qdel( front,rear) Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) 1. a. b. 2. 3. 4. a. 5. a. 6. 7. 8. Page 63 of 82 if front =NULL Display “Underflow” Exit Set item=front->info Set ptr=front If front=rear Set front=rear=NULL else Set front =front->next De-allocate ptr Display “the deleted element is “ ,item Exit Q21. Show the array implementation of a circular queue. 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 could be inserted. 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. Program implementing a circular queue: #include<stdio.h> #include<conio.h> #define max 5 int cq[max]; int front =-1,rear=-1; void insert(int n) { if((front==0 && rear==max-1)||(rear+1==front)) {printf("underflow"); getch(); return; } else if(front==-1) {front=rear=0; cq[rear]=n; } else if(rear==max-1) { rear=0; cq[rear]=n; } else {rear++; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 64 of 82 cq[rear]=n; } } void del() {if(front==-1) {printf("Underflow"); getch(); return; } else if(front==rear) front=rear=-1; else if(front==max-1) front=0; else front++; } void disp() {int i; if(front==-1) {printf("Underflow"); getch(); return; } if(rear>=front) { for(i=front;i<=rear;i++) printf("%d ",cq[i]); } else { for(i=front;i<=max-1;i++) printf("%d ",cq[i]); printf("<- "); for(i=0;i<=rear;i++) printf("%d ",cq[i]); } getch(); } void main() { clrscr(); insert(1); insert(2); insert(3); del(); insert(4); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 65 of 82 insert(5); del(); disp(); } Q22. Write insertion/deletion algorithm for a deque. Ans: In a deque, elements can be inserted at both ends Insertion from rear: Insertrear 1.1. If front==0 and rear=max-1 1.1.1. Write “Overflow” 1.1.2. Exit 1.2. Read item 1.3. if front=-1 1.3.1. front=rear=0 1.3.2. DQ[front]=item 1.3.3. Exit 1.4. if rear=max-1 1.4.1. I=front-1 1.4.2. while I < rear 1.4.2.1. DQ[I]=DQ[I+1] 1.4.2.2. I=I+1 1.4.3. DQ[rear]=item 1.4.4. front=front-1 1.5. else 1.5.1. rear=rear+1 1.5.2. DQ[rear]=item 1.6. Exit Insertion from front Insertfront 1.1. If front==0 and rear=max-1 1.1.1. Write “Overflow” 1.1.2. Exit 1.2. Read item 1.3. if front =-1 1.3.1. front=rear=0 1.3.2. DQ[front]=item 1.3.3. Exit 1.4. if rear != max-1 1.4.1. num_item=rear-front+1 1.4.2. I=rear+1 1.4.3. j=1 1.4.4. while j<=num_item 1.4.4.1. DQ[I]=DQ[I-1] Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 66 of 82 1.4.4.2. I=I-1 1.4.4.3. j=j+1 1.4.5. DQ[I]=item 1.4.6. front=I 1.4.7. rear=rear+1 1.5. else 1.5.1. front=front-1 1.5.2. DQ[front]=item 1.6. Exit Deletion from the front 1.1. 1.1.1. 1.1.2. 1.2. 1.3. 1.3.1. 1.4. 1.4.1. 1.5. 1.6. If front =-1 Print “Underflow “ Exit Set item=Deque[front] if front = rear Set front = rear= -1 else Set front =front +1 Print “Deleted element “,item Exit Deletion from the end 1.1. 1.1.1. 1.1.2. 1.2. 1.3. 1.3.1. 1.4. 1.4.1. 1.4.2. 1.4.2.1. 1.5. 1.6. If front =-1 Print “Underflow” Exit Set item=Deque[rear] If front=rear front=rear=-1 else rear=rear-1 if rear =-1 Set front = -1 Print “Deleted element “,item Exit Q23. Write a program to show linked list implementation of a Circular Queue. Ans. The program showing linked-list implementation of a circular-queue is as follows: #include<stdio.h> #include<conio.h> struct node { int data; struct node *link; }; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 67 of 82 void addcirq(struct node **f, struct node **r, int item) { struct node *q; q=(struct node*)malloc(sizeof(struct node)); if(q==NULL) { printf(“Overflow”); exit(); } q->data=item; if(*f==NULL) {*f=q; *r=q; q->link=*f; } else {(*r)->link=q; q->link=*f; *r=q; } } void delcirq(struct node **f, struct node **r) { struct node *q; if(*f==NULL) { printf(“Underflow”); exit(); } else { if(*f==*r) { free(*f); *f=NULL; *r=NULL; } else { q=*f; *f=(*f)->link; (*r)->link=*f; free(q); } } } void cirq_display(struct node *f) { Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 68 of 82 struct node *q=f; do { printf(“%d\n”,q->data); q=q->link; } while(q!=f); } void main() { struct node *front,*rear; clrscr(); front=rear=NULL; addcirq(&front,&rear,10); addcirq(&front,&rear,67); addcirq(&front,&rear,2); addcirq(&front,&rear,89); cirq_display(front); delcirq(&front,&rear); cirq_display(front); getch(); } Q24. a. b. c. d. e. f. g. h. i. j. Ans: Define the following terms: Root node Sibling nodes Ancestor and descendant Depth(or height) of a binary tree Strictly binary tree Internal and external nodes Complete binary tree 2-tree Degree of a node Path A B D F C E G Figure 1 Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 69 of 82 a: Root node- The node at the top of the tree having no parent, is called the root node. For eg. in the tree above, A is the root node. b: Sibling nodes- The nodes having the same parent are known as siblings. For eg. nodes D and E are siblings as they have a common parent, B. c: Ancestor and descendant nodes-- The parent of a node or the parent of parent is called an ancestor. For eg. in the above-mentioned binary tree, nodes B and A are the ancestors of node D. The child of a node or the child of the child node, is known as a descendant. If the descendant belongs to the left subtree, it is known as the left descendant and if it belongs to the right subtree, it is known as the right descendant. For eg. nodes D, E and F are the descendants of node B. d: Depth(or height) of a binary tree - It is the highest level number of any node in the binary tree. In the above-mentioned tree, the depth of the tree is 3. e: Strictly binary tree - It is a binary tree in which every node has either 0 or 2 child-nodes. A B C D E Strictly binary tree f: Internal and external nodes- The nodes having child nodes are called internal/non-terminal nodes whereas the nodes having no child nodes are called leaf/external/terminal nodes. For eg. in Figure 1 above, the nodes A, B, C, D are internal nodes whereas the nodes E, F and G are external nodes. g: Complete binary tree- It is a binary tree in which each level has the maximum number of nodes and all the leaf nodes of the tree are at the same level. At any level n of a binary tree, there can be at the most 2 n nodes. i.e.: At n=0, there can be at most 20 =1 node At n=1, there can be at most 21 =2 nodes At n=2, there can be at most 22 =4 nodes and so on.. A C B D E F G Complete Binary Tree h: 2-tree- Any strictly binary tree can be represented as an 2- tree by representing the leaf nodes in square shapes. It is also known as extended binary tree. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 70 of 82 A B C D E Extended Binary Tree i: Degree of a node--It is the number of child-nodes which a node has. For eg. in the tree given in Figure 1 above, the degree of node B is 2, degree of node C is 1. Degree of nodes F, E and G is 0. j: Path-- It is a sequence of edges between two nodes. For eg. in Figure 1 above, path from A to F is A->B->D->F Q25. Define binary search tree. Write the program for insertion into a binary search tree. Ans: It is also known as binary sorted tree. It is a binary tree in which for each node, the values of nodes in its left subtree are less the node-value and the values of nodes in its right subtree are greater than the node-value. 90 80 75 D 70 100 86 120 Binary Search Tree The program for insertion into a binary search tree is as follows: #include<stdio.h> #include<conio.h> #include<alloc.h> struct node{int info; struct node *left; struct node *right; }*root,*ptr,*loc,*par,*save,*nw,*suc,*parsuc; void find(int); void display(struct node*); void main() { char ch='y'; int n; clrscr(); root=NULL; while(ch=='y') { printf("Enter no"); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 71 of 82 scanf("%d",&n); fflush(stdin); find(n); if(loc!=NULL) {printf("Number already exists "); getch(); } else {nw=malloc(sizeof(struct node)); nw->info=n; nw->left=NULL; nw->right=NULL; if(par==NULL) root=nw; else if(n<par->info) par->left=nw; else par->right=nw; } printf("Enter another node"); ch=getchar(); fflush(stdin); } display(root); getch(); } void find(int n) { if(root= =NULL) {loc=NULL; par=NULL; return; } if(n= =root->info) {loc=root; par=NULL; return; } if(n<root->info) {ptr=root->left; save=root; } else {ptr=root->right; save=root; } while(ptr!=NULL) {if(n= =ptr->info) {loc=ptr; Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 72 of 82 par=save; return; } if(n<ptr->info) {save=ptr; ptr=ptr->left; } else {save=ptr; ptr=ptr->right; } } loc=NULL; par=save; } void display(struct node*p) { if(p!=NULL) { printf("%d ",p->info); display(p->left); display(p->right); } } Q26. a. b. c. Ans: Write the C functions for: Preorder traversal Inorder traversal Post-order traversal a: The C function for Pre-order traversal: void display(struct node*p) { if(p!=NULL) { printf("%d ",p->info); display(p->left); display(p->right); } } b: The C function for Inorder traversal: void display(struct node*p) { if(p!=NULL) { display(p->left); printf("%d ", p->info); display(p->right); Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 73 of 82 } } c: The C function for Post-order traversal: void display(struct node*p) { if(p!=NULL) { display(p->left); display(p->right); printf("%d ", p->info); } } Q27. Write the algorithm for bubble-sort. For the following sequence of elements perform bubble-sort. Ans: The algorithm for bubble-sort is as follows: 70,66,40,88,22 Algorithm BUBBLE (DATA, N) Here DATA is an array with n elements. This algorithm sorts the elements in DATA. 1. 2. 3. a) Repeat steps 2 to 4 for I = 0 to N-2 Set J: = 0 Repeat while J < (N-1)-I [Execute pass] If DATA [J] > DATA [J +1], then interchange DATA [J] & DATA [J+1] b) Set J: = J+1 4. Set I=I+1 5. Exit Applying bubble-sort on the above-mentioned elements, according to the algorithm above: In the first iteration,70 and 66 are compared and since 66 is smaller, they are interchanged, now 70 being in the second position, it is compared with 40 ,and 40 being smaller they are swapped. Again, now 70 being in the third position, it is compared with 88, but 88 being bigger, there is no swapping. Now, elements at 3 rd and 4th positions are compared and 22 being smaller than 88, a swapping is done. The sequence of elements becomes: 66 , 40, 70,22,88 Thus, after the first iteration, the largest element in the array, bubbles to the very end. In the second iteration, the 0th and 1st elements are compared and since 40 is smaller, 66 and 40 are swapped. After this, 66 and 70 are compared but no swapping is done. Further 70 and 22 are compared and a swapping is done. Thus the second-largest element takes its position after the 2nd iteration and this iteration stops here. The sequence of elements becomes: 40,66,22,70,88 In the third iteration, 40 and 66 are compared but no swapping is done.. Then 66 and 22 are compared and swapped. The third iteration ends here. And starting from the end, three elements have already been put in their proper positions. The sequence of elements becomes: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 74 of 82 40,22,66,70,88 In the last iteration, 0th and 1st position elements are compared i.e. 40 is compared with 22 and interchanged. The sequence of elements becomes: 22,40,66,70,88 Now the array is sorted. Q28. Write the program for insertion-sort. For the following sequence of elements perform insertion-sort. 25, 17, 31, 13, 2 Ans: The program for insertion sort is as follows: #include<stdio.h> #include<conio.h> #include<limits.h> void main() { int a[11],i,j,t; clrscr(); a[0]=INT_MIN; for(i=1;i<=10;i++) scanf("%d",&a[i]); for(i=1;i<=10;i++) { t=a[i]; j=i-1; while(t<a[j]) { a[j+1]=a[j]; j--; } a[j+1]=t; } for(i=1;i<=10;i++) printf(" %d",a[i]); getch(); } Applying insertion-sort on the above-mentioned elements on the basis of the algorithm, the sequence of elements becomes: INT_MIN,25,17,31,13,2 INT_MIN puts the minimum integer value at the first position in the array. Now 25 is compared with element previous to it, but since it is greater than INT_MIN, its position will be retained and the sequence of elements doesn’t change. In the second iteration, 17 is compared with 25 and since 25 is bigger than 17, 17 is compared with INT_MIN, but as 17 is bigger, the position of 17 is 1st in the array now and the sequence of elements becomes: Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 75 of 82 INT_MIN,17,25,31,13,2 In the third iteration, 31 is compared with 25 and since 31 is bigger, its position remains the same and the sequence of elements doesn’t change. In the fourth iteration, the next element 13 is picked up and compared with the elements previous to it, unless it comes across an element smaller than it, which is INT_MIN. So, 13 is inserted after the position of INT_MIN, and the sequence of elements becomes: INT_MIN,13,17,25,31,2 In the last iteration, 2 is similarly compared with its previous elements and in this case also all elements are bigger than 2 till it comes across INT_MIN. So, 2 is also inserted after the position of INT_MIN, and the sequence of elements becomes: INT_MIN,2,13,17,25,31 Thus the array is sorted in 5 iterations. Q29. Write the algorithm for quick-sort. Given the following sequence of elements, place the first element at its correct position, using quick-sort: 44, 33, 11, 55, 77, 90, 40, 60, 99, 22, 88, 66 Ans. The algorithm for quick-sort is as follows: Quicksort(A, beg, end) 1. if(beg<end) then 1. loc=Partition(A, beg, end) 2. Quicksort(beg,loc-1) 3. Quicksort(loc+1,end) 2. exit Partition(A, left, right) 1. loc=left 2. p=A[left] 3. Repeat steps 4 to 6 while left <right 4. while(A[left]<=p) and (left<right) a. left=left+1 5. while(A[right]>p) a. right=right-1 6. if(left<right) then a. swap(A[left],A[right]) 7. swap(A[right],A[loc]) 8. loc=right 9. return loc 10. The steps in finding the position of 44 are as follows: 44, 33, 11, 55, 77, 90, 40, 60, 99, 22, 88, 66 Beginning with the last number 66, scan the list from right to left, comparing each number with 44 and stopping at the first number less than 44. The number is 22. Interchange 44 and 22. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 76 of 82 22, 33, 11, 55, 77, 90, 40, 60, 99, 44, 88, 66 Beginning with 22, scan the list from left to right, comparing each number with 44 and stopping where number is greater than 44. The number is 55. Interchange 44 and 55 22, 33, 11, 44, 77, 90, 40, 60, 99, 55, 88, 66 Now beginning with 55, scan the list in original direction, from right to left. Stop when a number is less than 44. It is 40. Interchange 44 and 40. 22, 33, 11, 40, 77, 90, 44, 60, 99, 55, 88, 66 Beginning with 40, scan from left to right. First number greater than 44 is 77. Interchange them 22, 33, 11, 40, 44, 90, 77, 60, 99, 55, 88, 66 Beginning with 77, scan from right to left. We don’t meet any number less than 44. This means all numbers have been sorted according to 44. Thus 44 is correctly placed in its final position. Q30. Explain the different searching techniques. Give the advantages and disadvantages of these techniques. Ans: Searching is the process of finding data from a set of given data items. The different searching techniques are as follows: Linear Search Binary Search Hashing Linear Search: The linear search is a straightforward method of retrieving elements. This is often considered the simplest technique for searching an unordered list of elements. In linear search, the list is scanned element by element for the element to be retrieved. When an appropriate match is found, a message is displayed. A sequential search can be applied to any kind of list static or dynamic. Following are some of the properties of the linear search technique. The item to be found is called the key. The search function will return the index number (for a static list) or a pointer (for dynamic list) when item is found in the list. If the key cannot be found in the list, then not found value is returned eg. –1 for a static list or NULL for a dynamic list. Binary Search: In binary search, the data must be sorted, and the comparison starts at the middle. If the item is smaller than the middle, then search is carried out in the first half of the data. If the item is greater than the middle element, the search is carried out in the second half of the data. At each level, we keep leaving half the data, and calculate a new middle. This way of searching is highly efficient. The data-structure, arrays are best suited for performing binary search. Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 77 of 82 Comparison between linear search and binary search: Linear search is a simple method in which each element of the array is compared with the number to be searched. However, if the size of the array is big, and the number to searched is towards the end, this is a timeconsuming method. Since binary search begins with the middle-element, it reduces the number of comparisons needed to search an element and thereby is much faster than linear search, especially where the size of the array is big. However binary search requires that the array should be sorted and the computation of finding the middle-most element should be easy. These pre-requisites are not needed incase of linear search and thus for performing linear search, the data-structure could be an array or even a linked list. However, binary search is best suited for arrays. Hashing- This is another method of searching in which the key of the record to be searched is mapped to the record address. The function that transforms a key into a table-index is known as hash function. The commonly used hash functions are: Division method, Mid-Square method, Folding Method. The disadvantage of hashing is that it may lead to collision where-in two record keys are hashed into the same position. To avoid this, other techniques need to be used. However if the hash function is easy and quick to compute and leads to minimum collision, this is a very fast method for record-search. Q31. What is a max heap? Write the algorithm for performing heap-sort. Ans: A binary heap is a heap data structure created using a binary tree. It is called a max heap when it satisfies the following properties: 1) Shape Property: The tree is a complete binary tree. That is all levels of the tree, except possibly the last one are fully filled. 2) Heap Property: Each node is greater than or equal to each of its children, i.e. the value of each node is greater than the values of nodes in its left subtree as well as the right subtree. The algorithm for performing heap-sort is as follows: Heapsort(A,N) 1. Repeat for J=1 to N-1 a. Call Insheap(A,J,A[J+1] 2. Repeat while N>=1 a. Call Delheap(A,N,Item) b. A[N+1]=Item Insheap(A,N,Item) 1. N=N+1 2. ptr=N 3. Repeat steps 4 to 7 while ptr>1 4. par=ptr/2 5. If item<=A[par] then a. A[ptr]=Item Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) b. 6. 7. 8. 9. Page 78 of 82 return A[ptr]=A[par] ptr=par A[1]=Item Return Delheap(A,N,Item) 1. Set Item = A[1] 2. last=A[N] 3. N=N-1 4. ptr=1 5. left=2 6. right=3 7. Repeat steps 8 to 13 while right<=N 8. If last>= A[left] and last > A[right] then a. A[ptr]=last b. return 9. If A[left]>= A[right] a. A[ptr]=A[left] b. ptr=left 10. else 11. If A[right]> A[left] a. A[ptr]=A[right] b. ptr=right 12. left=2*ptr 13. right=left+1 14. If left= N and if last < A[left] a. A[ptr]=A[left] b. ptr=left 15. A[ptr]=last 16. return Q32. Write a program for merge-sort. Ans: The program for merge-sort is as follows: #include<stdio.h> #include<conio.h> void mergesort(int beg,int end); void merge(int beg,int mid,int end); int a[10]={310,285,179,652,351,423,861,254,450,520}; void main() {int i; mergesort(0,9); clrscr(); for(i=0;i<=9;i++) printf("%d ",a[i]); getch(); } Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 79 of 82 void mergesort(int beg,int end) { int mid; if(beg<end) { mid=(beg+end)/2; mergesort(beg,mid); mergesort(mid+1,end); merge(beg,mid,end); } } void merge(int beg,int mid,int end) {int i=beg,j=mid+1,k=beg; int b[10]; while(i<=mid && j<=end) {if(a[i]<=a[j]) {b[k]=a[i]; i++; k++; } else {b[k]=a[j]; j++; k++; } } while(i<=mid) {b[k]=a[i]; i++; k++; } while(j<=end) {b[k]=a[j]; j++; k++; } for(k=beg;k<=end;k++) a[k]=b[k]; } Q33. What are the steps to delete a node in BST? Write the C-function for deletion of a node. Ans: To delete a node from a binary search tree, there are four cases to consider: a) b) c) d) No node in the tree containing the specified data. The node containing the data has no children The node containing the data has exactly one child The node containing the data has two children. Case a) Print the message: data not found Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 80 of 82 Case b) Memory occupied by the node is freed Case c) Pointer of the parent of the node to be deleted points to the child of the node to be deleted Case d) The data of the inorder successor of the node to be deleted is put in place of the data of the node . Then the inorder successor is deleted. For example, deleting a node with only one child Before deletion: After deletion The C-function for deleting a node from a binary search tree is as follows: root, loc,par,ptr and root are global pointers of tree node-type of structure void del(int n) { struct node *loc; loc=find(n); if(loc==NULL) {printf("Number doesn't exist "); getch(); } Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 81 of 82 else { if(loc->left!=NULL && loc->right!=NULL) caseb(); else casea(&loc,&par); free(loc); } } void find(int n) { if(root==NULL) {loc=NULL; par=NULL; return; } if(n==root->info) {loc=root; par=NULL; return; } if(n<root->info) {ptr=root->left; save=root; } else {ptr=root->right; save=root; } while(ptr!=NULL) {if(n==ptr->info) {loc=ptr; par=save; return; } if(n<ptr->info) {save=ptr; ptr=ptr->left; } else {save=ptr; ptr=ptr->right; } } loc=NULL; par=save; } Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100 SUBJECT: ‘DATA STRUCTURE’ (BSC-IT - 2) Page 82 of 82 void casea(struct node**loc,struct node**par) { struct node *child; if((*loc)->left==NULL && (*loc)->right==NULL) child=NULL; else if((*loc)->left!=NULL) child=(*loc)->left; else child=(*loc)->right; if((*par)!=NULL) { if((*loc)==(*par)->left) (*par)->left=child; else (*par)->right=child; } else root=child; } void caseb() { struct node *ptr,*save,*suc,*parsuc; ptr=loc->right; save=loc; while(ptr->left!=NULL) {save=ptr; ptr=ptr->left; } suc=ptr; parsuc=save; casea(&suc,&parsuc); if(par!=NULL) { if(loc==par->left) par->left=suc; else par->right=suc; } else root=suc; suc->left=loc->left; suc->right=loc->right; } Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100