Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

C-1 Data Structures and Algorithms-I

Uploaded by

payalwani73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
45 views

C-1 Data Structures and Algorithms-I

Uploaded by

payalwani73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 65
S.Y. B .Sc aComputer Section-| Section-Il Expected Questions Paper Solutions 6q ps CHAPTERWISE YEARWISE Computer Science Paper-| Data Structures & Algorithms - I Mr. Mukesh C. Jain Mr. Suresh R. Agrawal B.Tech-IT, M.E.~Comp Engg., PhD(Per.) B.Tech-IT, SCJP, Programming Polyglot NSG Academy www.nsgacademy.in mukesh jain@netsecretsgroup.com = 75/- _©7> VISION PUBLICATIONS By Multiple Choice Questions (1 Mark Questions) : 2. A mathematical-model with a collection of operations defined on that model Is called a. Data structure b. ADT c. Primitive datatype d. Algorithm Which of the following Is true about the characteristics of abstract data types? i. It exports a type ii. It exports a set of operations. a. False, False b. . False, True c. True, False d. True, True Which of the following data structure is linear-type? fae List b. Stack c. Queue d. — Alllof the above Which of the following data structure Is non-linear type? a. Graph b. Tree c. Queue d. Bothaandb Data structure is a set of a. Functions and Axioms b. Data Objects and Functions c. Data Objects, Functions and Axioms d. Axioms and Data Objects S.Y. C-l Data Structures and Algo... « @ Introduction to Data Struct... ation 7. 10. 11. S.Y. C4 Data Structures and Algo... ¢ [EJ + Introduction to Data Struct... Which of the following Is good characteristics of Algorithm? 0: vision a. _ Definiteness b. Effectiveness c. Finiteness d. All of the above Which of the following Is correct? a. logn No. 2. What are advantages of ADT? (Apr. 2019, 2017, 2016) Solution Advantages of ADT i, Encapsulation Information hiding iii, Implementation details hiding 3. Define the following term: |. Data structure (Apr. 2019, Oct. 2018, 2017) I. Time complexity (Apri! 2016) Solution i, Data Structure: The triple (D, F, A) denotes the data structure d and it will usually be written as d. Where, Domain (D): denotes the data objects. S.Y. C-1 Data Structures and Algo..: # 7] # Introduction to Data Struct... yi i Functions (F): denotes the set of operations that can be carried out on the data objects. ‘Axioms (A): denotes the properties and rules of the operations. ii, Time Complexity: Time complexity of an algorithm signifies the total time required by the program to run to completion. The time complexity of algorithm is most commonly expressed using the big O notation. 4. What is ADT? (October 2018) Solution ADT is defined as a mathematical model of the data objects that make up a data type as well as functions that operate on these objects. ADT is the specification of logical and mathematical properties of a data type or structure. 5. Define the term Omega Notation(Q). (Oct. 2018, Apr. 2018) Solution A function f(x) is said to be Q (g(x)) if there exists two positive constants c and k such that f(x) 2 e(g(x)) whenever x 2k This gives lower bound for a given function. 6. Whatis ADT? What are the advantages of ADT? (April 2018) Solution In ADT, we encapsulate the data and the operations on data and we hide them from a user. Advantages of ADT: i, Encapsulation ii, Information hiding iii, Implementation details hiding 7. What Is meant by an abstract data type? (October 2017) Solution In abstract data type, we encapsulate the data and the operations on data and we hide them from auser. 8. Define Theta notation (6). (October 2017) Solution A function f(x) is said to be @ (g(x)) if, there exists positive constants ¢1, cy and k such that 2 BX) $ f(x) $c) g(x) for all x2 k. SY. C+ Date Structures and Algo... + (EJ + Introduction to Data Struct... 9. What are the components of space complexity? (April 2017) Solution Components of space complexity are as follows: i. Instruction space ii. Data space iii, Environmental stack space 10. What are different asymptotic notations? (April 2017) Solution Asymptotic notations are i. Big-O(O) ii, Big-omega (Q) iii, _Big-theta(®) 11. Define Data Object. (October 2016) Solution A data object is a region of storage that contains a value or group of values. Each value can be accessed using its identifier or a more complex expression that refers to the object. In addition, each object has a unique data type. Both the identifier and data type of an object are established in the object declaration. 12. Define Space Complexity. (October 2016) Solution Space complexity is the amount of computer memory required during the program execution. It is a function of the input size. Components of space complexity: The space needed by an algorithm is the sum of the following two components: Fixed Part: This is independent of the characteristics of the inputs and outputs. It includes the instruction space for simple variables, fixed size component variables, constants, etc. It specifies the compile-time space complexity. Variable Part: It consists of the space needed by variables whose size depends on the particular problem instance being solved, the space needed by referenced variables and recursion stack space. It specifies the run-time space complexity. S.Y.C-1 Date Structures and Algo... « J # Introduction to Data Struct... 92 13. Define the term Big O notation. (April 2016) Solution Let n be the size of the input and f (n), g(n) be positive functions of n. In Big O: f (n) is O(g(n)) if and only if there exists a real, positive constant C and a positive integer no such that f(n) $ Cg(n) Vn 219 Here O(g(n)) is a class of functions. The "O" notation specifies asymptotic upper bounds. It is a convenient way of describing the growth rate of a function and the time complexity of an algorithm. (ro vision Array as a Data Structure E}| Multiple Choice Questions (1 Mark Questions) : 1. What Is the worst-case time complexity of Bubble Sort? a O(n) b. O(n’) c. Oflogn) d. O(nlogn) 2. What Is the best-case time complexity of Bubble Sort? a O(n) b. O(n’) c. O(log n) d. O(n log n) 3. What Is the worst-case time complexity of Insertion Sort? a O(n) b. O(n’) c. O(logn) d. O(n log n) 4. What Is the best-case time complexity of Insertion Sort? a O(n) b. O(n’) c. O(logn) d. O(nlog ny 5. What Is the worst-case time complexity of Selection Sort? a O(n) b. O(n’) c. O(logn) d O(log n) 6. What Is the best-case time complexity of Selection Sort? a O(n) b. O(n’) c. O(log n) d. OMmlogn) 7. What is the worst-case time complexity of Quick Sort? a O(n) b. O(n’) c. O(logn) d. O(n logn) S.Y. C4 Data Structures and Algo... « © Array as a Data Structure ¢ Array as a Data Structure wen S.Y. Cl Data Structures and Algo... ¢ 8. What Is the best-case time complexity of Quick Sort? a O(n) b. O(n’) c. O(log n) d. O(n log n) 9. What Is the worst-case time complexity of Merge Sort? a O(n) b. O(n’) c O(log n) a. O(n log n) 10. What Is the best-case time complexity of Merge Sort? a O(n) b. Om’) c. Oflogn) d. O(n log n) 11. What Is the worst-case time complexity of Radix Sort? a =O) b. Om’) c. O(log n) 4. O(mlogn) 12, What Is the best-case time complexity of Radix Sort? a. O(n) b. O(n’) c. O(log n) d. O(logn) 13. What Is the worst-case time complexity of Count Sort? a On) b. O(n’) c O02’) ad O(n+k) 14, What is the best-case time complexity of Count Sort? a O(n) b. Om’) © — O(2") da. O(n+k) BO) Answer the following (1 Mark Questions) : | Marks for these Questions may vary from 1 to 2. 1. State any two limitations of an Array. (April 2019) Solution i. An array is a static data structure, i.e., the size of the array remains fixed. It cannot be increased / decreased during runtime. ii, Array do not support insertion and deletion of data. Because, insertion or deletion in array Tequires shifting of data by one position which will take lot of time. S.Y. C-l Data Structures and Algo... + # Array as a Data Structure ol 2, What is time complexity of Quick Sort? (October 2018) Solution Time Complexity Of Quick Sort are i. Best Case: O(n log; n) ii, Worst Case: O(n*) a ae is worst and best time complexity of merge sort? (April 2018) ution Worst case and best case complexity of merge sort: i, Worst case - O(n log n) ii, Best case - O(n log n) 4. What Is time complexity of bubble sort? (October 2017) Solution Time complexity of bubble sort Best case = O(n*) Worst case = O(n*) Average case = O(n") 5. Define stable sorting. (April 2017) Solution A sorting method is said to be stable if at the end of the method identical elements occur in the same order as in the original unsorted set. 6. How are the elements of an array stored in memory? (April 2017) Solution Array elements stored in memory are sequential (continuous) which may be i Rowwise or ii. Columnwise. 7. What is time complexity of merge sort? (April 2016) Solution Merge sort is based on the divide-and-conquer paradigm. When the two halves are returned they will have been sorted. They can now be merged together to form a sorted array. Its worst-case running time has a lower order of growth than insertion sort. Consider an array to sort Alp...1]: Time complexity of merge sort is as Best case: O(n log(n)) Worst case: O(n log(n)) : O(n login) Average ca S.Y. C-I Data Structures and Algo... « © Array as a Data Structure oh vision G| Answer the following (5 Marks Questions) : Marks for these Questions may vary from 4 to 5. 1. Show all the steps of solving the following data using quick sort 26, 35, 24, 31, 11, 27, 19 (April 2019) Solution i. Initial 35 | 24 | 31 | 11 | 27 | 19 * 26 35 24 31 M27 19 ' j * 26 1924 31 11 27 35 ra i 31 © 26 19 24 27° «(35 ii Now, 3 1. 19, 24, [26] 31, 27 35 —~— piv SY 0 1 2 3 4 5 6 ii. Initial 11] 19 | 24 26 31 | 27 | 35, 1 uj pending S.Y. C-l Data Structures and Algo... * | @ Array as a Data Structure Oe wsion Now, 0 [i] 19, 24 pivot 1 2 iii, Initial 19 | 24 lou j 19 i jo t © 19, 24 i Now, 1 19] 24 pivot ~~ 2 iv. 24 pivot v. Now, Now, remaining of (ii) iteration. 4.5 6 Initial 31 | 27 | 35 1 uj 31 i j « 31 27° 35 i 27 Bi) 35 ~ pivot “7 27 pivot S.Y.C-1Data Structures and Algo... + — RJ «Array as e Data Structure ution 35 pivot So, we get final sorted data as 0 1 2 3 4 5 6 11 | 19 | 24 | 26 | 27 | 31 | 35 In quick sort, we select starting element as a pivot element and starting element as i and next to last element j We increment i upto we get element greater than pivot and decrement j till we get element less than pivot. If we get such element and i and j do not cross each other then we interchange them, but if i and j crossed each other then we replace pivot element with j® element and we get two Partitions. One partition contains elements greater than pivot and another partition contains elements less than pivot. Now, sort each partition by using above steps. We get sorted elements at the end. 2. What are the different ways of representing 2D arrays In memory? Give the formula for address calculation. Explain with example. (April 2019) Solution Arrays can be physically represented in two ways: 1. Row-major representation: In this representation, the elements are arranged row-wise i.€. elements of row O are stored first, elements of row | are stored next and so on. 2. Column-major representation: Elements are arranged column-wise ie. elements of column 0 are stored first, elements of column 1 are stored next and so on. The following diagrams show the logical and physical view of a two-dimensional array. Logical View Columns—> 0 1 2 Rows ofa] als 4} 5) 6 2) 7) e8]9 3/10) 11] 12 | SY.C4 Data Structures and Algo... «+ EI Arrayas.a Dota Structure Physical View: Row Major Representation Oe wision 1/2/3/4]5]6}7)8| 9 ]10] 11] 12 |e Row 0—><— Row 1—>4e— Row 2—>— Row 3 I | Physical View: Column Major Representation 1/4] 7]10] 2] 5] 8) 11) 3) 6] 9] 12 {Column oe Column 1—2¢— Column 2—> Address Calculation For an array int a{r}{c]; where r = number of rows and c = number of columns, the location of an element a{i){j] in the array can be calculated as: i, Row Major Representation address of a [i] [j] = Base-address+ i*cxelementsize + jxelementsize = Base-address + (ixc+j) * elementsize Example address of a[1][2] = 1000 + (1*3+2) « sizeof(int) = 1000+10 = 1010 ii. | Column Major Representation address of a[i}{j] Base-address+ j+r*elementsize + i*elementsize Base-address+ (j+r + i)* elementsize Example address of a[1][2] = 1000 + (2*4+1) ssizeof(int) = 1000+ 18 = 1018 3. Sort the following data using bubble sort: 13,12,14,15,19,9. (October 2018) Solution Insertion sort - 13,12,14,15,19,9. Pass -1 13°12 14 «15 19 9 LJ 12°13 14 15 19 9 ‘S.Y. C-l Data Structures and Algo... 12 13 14 15 1213 14 15 12 13 14 15 12, 13, 14, 15,9,19 Pass - II 12°13 14 15 12°13 14 15 2 19) 14515: 12) 19b 14219) 12,13,14,9,15,19 Pass - 0 N2E 192 14.9) 12 13 14 9 12,13,9,14,15,19 Pass -IV 12 13 9 14 1219 9 14 12,9,13,14,15,19 19 9 19 19 9 9 9 9 15 15 9 9 19 19 19 © Array as a Data Structure iz ‘vision S.Y. C-l Data Structures and Algo... ¢ @ @ Array as a Data Structure Pass - V 4. 12 9 13 14 15 19 9, 12, 13,14,15,19 Write a short note on searching methods. (October 2018) Solution Searching is one of the most basic operation performed by a computer. Searching is the process of retrieving or locating information matching some specific criteria or value. Usually the search is done on the basis of a ‘key’ value which is a unique entity which identifies the data. A successful search is called retrieval. Two important searching methods are as follows: Linear Search Binary Search Linear Search Procedure: In this method, the searching begins from the first element or record. The Tequired key value is compared with the record key. Searching continues sequentially till the record with a matching key value is found or if the data ends. Efficiency Best Case: O(1). Worst Case: O(n). Advantages © Itis a very simple method. © Itdoes not require the data to be ordered. Disadvantage . Itis very inefficient. © Ifnis very large, this method is very slow. Binary Search Pre-requirement: Data has to be in the sorted order. Procedure © In this method, the set of elements is partitioned into two equal parts and the required key is compared with the key of the middle record. If a match is found, the search terminates. 2. S.Y. C-4 Data Structures and Aigo... + ¢ Array as a Data Structure wien . If the key is less than the middle key, the search proceeds in the top half of the table. © If the key is greater than the middle key, the search proceeds in the same way in the lower half of the table. © The process continues till no more partitions are possible. Thus every time a match is not found, the remaining table size to be searched reduces to half. Best Case: O(1) Worst Case: O (log; n) Advantage * Time complexity is 0 (log,n) which is very efficient. © Does not require any additional data structure. Disadvantages © Data has to be in sorted manner. * This method can only be applied to sequential or linear data structure. 5. — Sort the following elements using Insertion Sort (write passes): 23, 6, 18, 29, 27, 4,13 (April 2018) Solution Insertion sort - 23, 6, 18, 29, 27, 4, 13 Pass -1 23:6 18 29 27 4 13 6 is compared with 23 as 23 > 6 so interchange them 6 23 18 29 27 4 13 Pass - II 6 23 18 29 27 4 13 18 is compared with 23and6 © 23>18 True 6>18 False 6p 16.29) 20) 27,4213) Pass — 6 18 23 29 27 4 13 29 is compared with 23, 18 and 6 respectively iz ‘S.Y. C+ Data Structures and Algo... ¢ whan 23>29 False 18>29 False 6>29 False No change. 6 18 23 29 27 4 13 Pass - IV 6 18 23 29 27 4 13 27 is compared with 29, 23, 18 and 6 respectively 29>27 Tre 23>27 False 18>27 False 6>27 False 6 18 23 27 29 4 13 Pass - V 4 is compared with 29, 27, 23, 18 and 6 respectively 29>4 Tre 27>4 Tre 23>4 Tre 6>4 Tre 4 6 18 23 27 2 13 Pass - VI 4 6 18 23 27 29 13 13 is compared with 29, 27, 23, 18, 6 and 4 respectively 29>13 True 27>13 Tre 23>13 True 18>13 True 6>13 False 4>13 False 2/6) 19) 18). 235.27, 1.29) 6. Write an algorithm for Binary search. (April 2018) Solution //initially called with low = 0, high = N- 1 BinarySearch(A{0 . . . N - 1], value, low, high) 2. * Array as a Data Structure Sion S.Y. C-I Data Structures and Algo... if(high < low) return not_found mid = (low + high) /2 if(A(mid) > value) return BinarySearch(A, value, low, mid - 1) else if(A[mid] < value) return BinarySearch(A, value, mid + 1, high) else return mid ) 7. Sort the following numbers using Insertion sort method: 30, 40, 10, 50, 25, 35, 15. (October 2017) Solution Insertion sort - 30, 40, 10, 50, 25, 35, 15 Pass -I 30 40 10 50 25 35 14 40 is compared with 30 30>40 False 30 40 10 50 25 35 15 Pass - IT 30 40 10 50 25 35 15 10 is compared with 40 and 30 40>10 True 30>10 True 10 30 40 50 25 35 15 Pass - 0 10 30 40 50 25 35 15 50 is compared with 40, 30 and 10 as 40>50 False 30>50 False 10>50 False 10 30 40 50 25 35 15 Pass ~ IV 25 is compared with 50, 40, 30 and 10 respectively as S.Y. C-l Data Structures and Algo... « 7K} 50> 25 40> 25 30> 25 10>25 10 25 30 40 50 35 15 Pass - V 35 is compared with 50, 40, 30, 25, 10 as 50>35 40 > 35 30>35 25>35 10>35 10 25 30 35 40 SO 15 Pass - VI © Array as a Data Structure win Tre Tre True False True True False False False 10 25 30 35 40 50 15 15 is compared with 50, 40, 35, 30, 25, 10 as S0>15 40> 15 35>15 30>15 25>15 10>15 10 15 25 30 35 40 50 8. — Sort the following data using quick sort: 12, 24, 9, 46, 31, 53, 33. Solution __| isgreater 12} 24 9 46 3 53 i & 9 2 46 31 «53 (9) 12 [24 46 a 53 True Tre Tne Tne True False (April 2017) less © j 33 33 i i-iand j crossed each other. <. feplace pivot element with j 33] Data Structure OQ» S.Y. C- Data Structures and Algo... © es] ¢ Array Here we get two sorted list i j i 9 12 (Za) 46 31 58 33] 9 12 24 3153 33] 9 12 24 (ae) 31 (388) 9 12 24 (Gal 31) (46 53] 9 2 2 031 [33] 46 83 9 12 2 031 33 4888 woe ce ath In quick sort, we select starting element as a pivot then element next to pivot is i" element and last element is j* element. We increment i till we get element greater than pivot and decrement than pivot. If we get such element, i and j do not cross each other then we interchange them, but if i and j crossed each other then we replace pivot element with j* element and we get two lists. One list contains elements greater than pivot and another list contains elements less than pivot. j till we get element less Now sort each list separately by using above rules. We get sorted elements. 9. Write an algorithm for binary search. Also state Its complexity. (April 2017) Solution Algorithm Binary Search (Recursive) Binarysearch(A[0...N-1], value, low, high) ( if (high (low) ) return not_found mid=(Llow + high) /2; if(A[mid] > value) return Binarysearch(A, value, low, mid-1) else if(A{mid] < value) return Binarysearch(A, value, mid+1, high) else return mid; ) Complexity The maximum number of key comparison is log:n. :. Complexity is O(log,) S.Y. C4 Data Structures and Algo... « MEY « Arrayasa Data Structure wien log N: Typically achieved by dividing the problems into smaller segments and only looking at one input element in each segment. 10. Sort the following elements using Bubble Sort: (Write all passes) 91, 21, 41, 71, 51, 31, 81. (October 2016) ‘Solution The basic idea behind Bubble sort is to pass the list sequentially several times. In each pass compare successive pairs of elements (x{i] with x[i+1]) and interchange the two elements if they are not in required order. One element is placed in its correct position in each pass. In subsequent passes, we consider one element less than the previous pass. A total of n-1 passes are required to sort ‘n’ keys. In first pass, the largest element will sink to the bottom, second largest element in the second pass and so on. Start comparing from first pair of elements from the given data as follows The given data is 91, 21, 41, 71, 51, 31, 81 Pass 1: * at 21 21 at tt at "4 Aiea eae Ale 4 | 44 41 ot] ile 7a eel el ipaeriaiae 7! 2) 515151 Slee ote Olena! ou] aieae ol 31 31 31 (31 31 ea] 81 gi 8t) ts Bt BT BI 8. Pass 2: Ps a) ai) 7m 74 ch 51 51 51ST st 51 51 a at 31 8t 3131 8tt zu] 7” 71 et 8f 8188 aT a1 ot of 91 91 «91 «81 Ot 2 @ Array as a Data Structure wien S.Y. Cl Data Structures and Algo... ¢ Pass 3: am 210 2t at ot att il 41 410 410 41 att 51 al 4 Slee oles ato 31 31 8t 4 51 5151 lee? eee 4 ma 71 Sieesl ee oieerclnnae | 4 81 91 91 91 tt tot Pass 4: 29 21 at at ott ad 415 31 310 31 t8t 31 eal 419 440 44 at 51 51 a 4 51 51 51 mam mt oT a) ma 74 81 81 at tat et 81 1 91 91 ot oot att ot Pass 5: 4 21021 at oat oat oat 31-34 il Sie ieee ol eS en 4y 44 “7 440410 44a S151 St aa 515154 mom om 7m ca m7 81 81 818g a 81 91 91 91 toto gt Pass 6: eal] 21210 Ot katt 31 4 31031 81 at 44 a) a o4at oat oat 51514. ot) St 5151 mom om 7m a mon 81 81 «Bf 81st 4 81 1 9 91 ott tt gy 11, Show all the steps of sorting the following data using quick sort 24, 30, 27, 32, 11, 21, 19. (Apri 2016) Solution (April 20 Quick sort uses two algorithms for sorting as: .Y. C-1 Data Structures and Algo... + b-ril ¢ Array as a Data Structure when Divide: Rearrange the elements and split the array into two subarrays and an element in between so that each element in the left subarray is less than or equal the middle element and each element in the right subarray is greater than the middle element. Conquer: Recursively sort the two subarrays. Algorithm for Conquer as quicksort (int if (upper > 10% (a: lower, int upper) - 7 upper) ; Algorithm for Divide as int split(int a{], int lower, int upper) ( lower + 1; upper; allower]; while(q >= p) { while (a(p] p) ( t= alpli a(p) = all: alq) =t; i 1 t = allower); allower] = alql; - alq] = tj return qj } Given data is as 24, 30, 27, 32, 11, 21, 19 Here, lower = 0 and upper According to algorithm, divide this array into 2 parts as compared to pivot element. Take first element from arrays as pivot element. Soi=24,p=1andq=6 While p pivot value then decrease q value. Otherwise swap a[p] and aq] if q>p On S.Y. C4 Data Structures and Algo... + EJ ¢ Arrays a Data Structure wision Applying this algorithm, We get array as 24, 19, 27, 32, 11, 21, 30 where p = I and q=6 Now, a[p] < pivot so increase p = 2 and q= 5 Swap afp] and a{q] 24, 19, 21, 32, 11, 27, 30 where p = 2 and q=5 Now alp] next) ; printf("%d ", head->data); ) a. Prints all nodes of linked lists b. Prints all nodes of linked list in reverse order c. Prints alternate nodes of Linked List d. Prints alternate nodes in reverse order Which of the following points Is/are true about Linked List data structure when It is compared with array. a. It is easy to insert and delete elements in Linked List b. Random access is not allowed in a typical implementation of Linked Lists c. The size of array has to be pre-decided, linked lists can change their size any time d. —Alllof the above Which of the following Is not a type of Linked List? a Hybrid Linked List b. Circular Linked List c. Doubly Linked List d.— Singly Linked List Linked list Is generally considered as an example of type of memory allocation. b. Compile Time d. None of these a. Static ec. Dynamic Which Is invalid statement for array and linked list? Array and linked list are both non-primitive data structure. a. An array is a fixed size sequenced collection of elements of the same type. Linked b. list is an ordered set of a variable number of elements. Array has homogenous values. And each element is independent of each other positions. Each node in the linked list is connected with its previous node which is a pointer to the node. d. Array and linked list have homogenous values. And each element is independent of each other positions. S.Y. C-l Data Structures and Algo... @ Linked List DB Answer the following (1 Mark Questions) : | Marks for these Questions may vary from 1 to 2. 1. Explain node structure of SLL. (April 2019) Solution typedef struct node { int data; struct node ‘next; ) NODE; 2. Write node structure for a Doubly Circular Linked List. (April 2018) Solution typedef struct dnode ( int data; struct dnode * next, * prev; } DNODE; 3. “A Linked List can only be traversed sequentially”. State True/False. (April 2018) Solution True, because linked list contains next or previous nodes address as per the type of linked list. Therefore, linked list can either traverse in forward or backward direction, but sequentially. 4, What Is need for header? (October 2017) Solution A linked list must always have atleast one pointer pointing to first node (header node) of the list. This pointer is must because we don’t have another way to access the linked list. This pointer is called head node since, it is dummy node attached at the start position. 5. Define node structure of a singly linked list. (October 2017) Solution Structure of a singly linked list typedef struct node { int data; struct node * next; ) NODE; S.Y. C-l Data Structures and Algo... ea @ Linked List 6. What Is circular linked list? (April 2017) Solution A linked list is said to be circular if the last node of the linked list points to the first node. read 19 { 20 {30 Circular linked list 7. Write node structure of doubly linked list. (April 2017) Solution The node structure for a doubly linked list is, struct Node { struct Node *prev; /* backward pointer */ int info; /* data part */ struct Node *next; /* forward pointer */ he This structure is called as self-referential structure. The pointer next stores the address of the next Node and pointer prev stores the address of previous node. 8. What are applications of Linked List? (October 2016) ‘Solution Linked list can be used in many applications like 1. Linked list used for implementing stack, queue, graph, hash tables. 2. All the running applications are kept in a circular linked list and the OS gives a fixed time slot to all for running. The Operating System keeps on iterating over the linked list until all the applications are completed. 9. ‘Linked list can only be traversed sequentially’. State True/ False. (Apri! 2016) Solution True. The elements of linked list are stored sequentially in memory, items in a list may be located anywhere in memory. To access elements in correct order, we store the address or location of the next element, with each element of the list. The elements of the list are logically next to each other, but physically, they may not be adjacent. S.Y. C-l Data Structures and Algo... ¢ @ Linked List or G| Answer the following (5 Marks Questions) : | Marks for these Questions may vary from 4 to 5. 1. Write a 'C’ function to Insert and delete an element at particular Position in SLL. (April 2019) Solution i. Insert at specific position Function void insert (NODE *head, int num, int pos) { NODE ‘*newnode, *temp; int i; /* Move temp to node at pos-1 */ for(temp=head, i=1; (temp!=NULL)&&(i<=pos-1); i++) temp = temp->next; if (temp==NULL) ( printf ("Position is out of range"); return; ) newnode = (NODE *)malloc(sizeof(NODE)); newnode->info = num; newnode->next = temp->next; temp->next = newnode; ) Delete by position Function void deletepos (NODE “head, int pos) { NODE ‘temp, *templ; int i; /* Move temp to node at pos-1 */ for(temp=head, i=1; (temp->next !=NULL) &&(i<=pos-1); i++) temp = temp->next; if (temp->next==NULL) { print£("Position is out of range"); retur: temp1=temp->next; temp->next = templ->next; free (temp); } 2. Write a short note on Generalized linked-list. (October 2018) & sony at generalized linked list? Explain with example. (April 2017) mn a, which is denoted by A linear list is defined as a finite sequence of elements (n >= 0) aj, ax, A= (ai, az, ... a,), Elements of the linear list are atomic in nature. S.Y. C- Data Structures and Algo... # | oe won Elements of the linear list can be addressed by its index. A= ()— Anempty of null list B= (a,b, c)— A list of three elements with B(1) = a, B(2)= band B(3) = C. Ina generalized list, each element a, is either an atom or a list itself. C= (a, (b, ©), d) —A list of three elements First element ‘a' is atomic Second element (b, c) is list Third element ‘d' is atomic Thus, a generalized list, A is finite Sequence of n >= 0 elements a, a2, ... a, where each a, is either an atom or a list, a is said to be the head of A. (@1, 2, ... aq) is called tail of A. Example: i, A=(a,b,c) head oa ae o ° —> NULL ii, B=(a, (de), ¢) hea fa > head Fle +s nut EH NULL head }—sf ce} > nu ii, C=(d,e),(e,f),c) [head 2 |-H-HE AH NULL N é 5 S.Y. C-l Data Structures and Algo... + Linked List whan 3. | Write ‘C’ function to reverse a linked list. (October 2018), & Write a ‘C’ function to reverse singly linked list. (April 2017) Solution node * invert (node*head) { node *p, "qd, “IF p = NULL; q = head; r = qonext; /* initial values of p, q andr * while(q!= NULL) /* until all nodes have been reversed */ { qrnext = p; /*move p, q, forward by a node */ P= @ q=r; if(r!= NULL) r= rnext; ) return (p); } 4. Write a ‘C’ function to display even element (data) in a single linked list of integer. (April 2018) Solution void print (node *p) { while(p!= NULL) ( if((podata)%2 == 0) { printf ("e%d3", podata); Pp = ponext; ) else P = ponext; ) ) ) 5. Writea Solution Structure of a node in Doubly Linked List as, struct node { function to create a Doubly Linked List. (October 2016) struct node *llink; int data; struct node *rlink; } *head=NULL; Every node is created in Doubly Linked list using the following function as, void create(int n) { int i; S.Y. C-l Data Structures and Algo... ¢ D Linked List struct node *temp, *next; for (i=0;i1link=NULL; head->rlink=NULL; } else //if head is with some address { next=head; while (next->rlink!=NULL) { next=next->rlink; } next->rlink=temp; temp->llink=next; Write a ‘C’ function to perform addition of elements at even position In a doubly linked list of Integers. (April 2016) Solution Structure of a node in doubly linked list as struct node { int data; struct node *next, *prev; } *head; //function to perform addition of elements at even position in doubly //linked list of integers is as follows void cal_sum() { struct node *ptr; int sum; float avg; sum=0; int cnt=1; ptr=head; while (ptr!=NULL) { if (cnt%2==0) { sum=sum+ptr->data; } ptr=ptr->next; ent+4+; } printf("Sum is:%d", sum); } BD Multiple Choice Questions (1 Mark Questions) : 1. 3. Stack Is referred as a. Last in first out list b. First in first out list c. Both (a) and (b) d. none of the above In the stack process of Inserting an element in the stack Is called as a. create b. push c. pop d. evaluation Stack Is useful In a. Expression evaluation b. Handling of recursion c. both (a) and (b) d. none of these User perform following operations on stack of size 5 then - push (1); Pop (); push (2); push (3); Pop () 7 push (4); Pop (); Pop (); push (5); at the end of last operation, total number of elements present in the stack are — a ool bo 2 ec 3 . da 4 7 S-Y. C4 Data Structures and Algo... « © Stack whe 10. 11. Stack vision Consider Stack is implemented using the array. #define MAX 10 struct STACK { int arr[MAX]; int top = ) S.Y. C4 Data Structures and Algo... What will be the initial value with which top Is initialized? a. Garbage bo c -1 d 0 The postfix form of the expression (A+ B)*(C*D- E)*F / Gis? a. AB+ CD*E - FG /** b. AB + CD* E-F**G/ Cc AB + CD* E-*F*G/ d. AB + CDE * - * F*G/ The prefix form of A-B/ (C * D AE) is? a. -/*NACBDE b. -ABCD*ADE c -A/B*CADE d. -A/BC*ADE Convert the following Infix expression to Postfix form using a stack x +y*Z+(p*q+r)*s, Follow usual precedence rule a xyz*+pq*rts+ db. _xyz*+pq*res+* c. xyet*pq*r+s*+ d. none If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, in what order will they be removed? a. ABCD b. DCBA c. DCAB d. ABDC Which is the pointer associated with the stack? a. First b. Front c. Top d. Rear Time complexity of push operation on a stack is a a O(1) b OM) c. O(logn) dO’) S.Y. C4 Data Structures and Algo... ¢ | Marks for these Questions may vary from 1 to 2 1. State the Principle on which stack works. Solution . * Stack Di) Answer the following (1 Mark Questions) : on vision (April 2019) Stack works on LIFO principle, i.e.. the element which is inserted last will be deleted first. In stack, insertion and deletion of element is performed at one end, i.e., top of stack. 2. Consider operations performed on a stack push(1),push(2), pop, Push(1),push(2), pop, pop, pop, push(2), pop. What Is the sequence of Popped out values are? Solution | | | | 2 | top 4 1 top 1 1 top 1 push(1) pushi(2) pop push 1 | | 2 «top 1 1 top 1 1 1 ‘top push(2) pop pop Pop 2 top top push(2) Pop +. Sequence of popped values are: 2, 2, 1, 1,2 3. List different operations of stack. Solution Operations of stack i, create(s): create an empty stack. ii, push(e, s): add element in stack. (October 2018) top top (April 2018) S.Y. C4 Data Structures and Algo... # B @ Stack vision iii, pop(s): remove element from stack. iv. empty(): to determine stack is empty or not. Vv. full: to determine stack is full or not. 4. What are postfix and prefix forms of the expression? (October 2017) A+B*(C-D)/(P-R) Solution Postfix A+B*(C-D)/(P-RA) | A+B*(C-D)/(P-R) A+B*(CD-)/(PR-) | A+B *(-CD)/(-PR) A+B°CD-/PR- | A+B*-CD/-PR A+BCD-"/PR- | A+°8-CD/-PR A+/*B-CD-PR ABCD-"PR-/+ | +A/*B-CD-PR 5. Define stack. List out two operations of stack. (October 2017) Solution It is a LIFO data structure. In stack, insertion and deletion of element is performed at one end i.e. top of stack. Operations of stack i, create(s): create an empty stack. ii, push, s): add/insert element on stack. iii, — pop(s): remove/delete element from stack. 6. Name the data structure used In recursion. (April 2017) Solution Data structure used in recursion is stack. 7. Define the following term: (April 2017) Multiple stack Solution Multiple stack: Several stacks can be stored in a single array. Suppose A(] is an array of size MAX and N number of stacks are to be stored in the array. MAX is predefined constant. We can divide the available memory A[0 ... MAX — 1) into N segments. Each stack can be allocated one of these segments. This concept is called multiple stack representation in a single array. S.Y. C1 Data Structures and Algo... J # Stack wks 8, Write any two applications of stack. (October 2016) Solution Applications of Stack i, Expression Evaluation: This study of arithmetic expression evaluation is an example of problem solving where you solve a simpler problem and then transform the actual problem to the simpler one. ii. Backtracking (game playing, finding paths, exhaustive searching): Backtracking is used in algorithms in which there are steps along some path (state) from some starting point to some goal. a. Find a path from one point in a graph (roadmap) to another point. b. Play a game in which there are moves to be made (checkers, chess). 9. Convert the following expression: ((A +B) *C — (D — E) * (F + G) to equivalent postfix notation. (April 2016) Solution ‘The given infix expression is not well parenthesis. However, in postfix expression parenthesis is not present. So the postfix expression is AB+C*DE-FG+"~{ by considering the priorities of operators. G| answer the following (5 Marks Questions) : | Marks for these Questions may vary from 4 to 5. 1. Convert the Infix expression A * B $ C + D * E/F Into postfix expression. Assume §$ for exponentiation and has highest priority. (April 2019) Solution Steps | Symbol | Operator stack | Postfix expression 1 [A Empty A 2 T* Q A 3 [8 : 4 |s $ AB 5 |c 8 ‘ABC 6 |+ + ABC $+ 7 |b + ABC $:D a |: ABC $-D 9 |e + ABC $:DE to [7 + ABC $-DE- 1 [F + ABC $-DE-F 12 Empty ABC $*DE+F/+ ‘S.Y. C- Data Structures and Algo... # b5| @ Stack Step 1: Add A to postfix. Step 2: Push operator « onto the stack. Step 3: Add B to postfix. Step 4: Push operator $ onto the stack, it has higher precedence than *. Step 5: Add C to postfix. O. sion Step 6: Pop $ and = from stack and add in postfix and then push operator + because precedence of + is not higher than precedence of $ and #. Step 7: Add D to postfix. Step 8: Push + onto the stack, it has higher precedence than +. Step 9: Add E to postfix. Step 10: Pop « from stack and add it in postfix and push / onto stack, because precedence of / is not higher than precedence of « step 11: Add F to postfix. Step 12: Pop / and + from stock and add in postfix. ©. Hence, final postfix string is | ABC $*DE*F/+]. 2. — Give the output of the following code. Int I = 1, x, y; Initstack(); while(I<=5) { Push(i * 5); l=l41; } x = POP(); x = POP(); Push(i * 5); y = POP(); Push(x + y); x = POP(); y = POP(); Push(x + y); whlle(!stackempty()) printf("%d",POP()); (April 2019) 2. S.Y. C+ Data Structures and Algo... + Stack wie Solution © initstackQ) [2] | i x -1 © top | © while(ic =5) 4| 25 | top ( 3} 20 Push(i * 5); 2/15 6 isi+l; 1] 10 i x } Olea) © x=POP() 3| 20 | etop 6 25 2/15 i x 1] 10 of 5 © x=POP() 2| 15 | —top 6 20 1/10 i x o[ 5 + Pushii* 5) 3| 30 | top 6 | [20 2 1s i x 1/10 of s S.Y. C4 Data Structures and Algo... ¢ ° y=POP() 2 1 0 © Push(x + y) 3 2 1 0 © x=POP() 2 1 0 «© y=POPQ 1 0 © Push(x +y) 2 1 0 ¢ while(!stackempty()) printf("%d", POP); -1 Result: 65 105, 3. Write Solution #include typedef struct node { B+ suck 15 | < top 6 | 20 30 L 10 i us y 5 50 |< top 6 20 30 15 i x y 10 5 = 15 | top 6 50 30 10 i x y 5 10 | top 6 50 15 5 i x y © top 6 50 15 10 i x y 5 top program to Implement stack using singly linked list. Bs (October 2018) S.Y. C- Data Structures and Algo... # o @ Stack int info; struct node *next; ) NODE; NODE *top; void initstack() { top= NULL; } int isempty() { return (top == NULL); } void push(int num) { NODE * newnode; newnode= (NODE *)malloc (sizeof (NODE) ); newnode->info=num; newnode->next=top; top=newnode; ) int pop() { int num; NODE *temp=top; num =top->info; top=top->next; free (temp) ; return num; } void main() { int choice, nj initstack(); do { print £ ("1:PUSH\n2:POP\n3:EXIT\n") ; printf ("Enter your choice :"); scanf ("%d", &choice) ; switch (choice) ( case 1: /* PUSH */ printf ("\nEnter the element to be pushed : scanf ("%d",&n); push(n); break; case 2 :/* POP */ if (isempty ()) printf£("\nStack is empty "); else print£("\n Popped element : %d", pop()); break; } } while (choice!=3); d > S.Y. C-I Data Structures and Algo... # + Stack 4. Consider given Infix expression(u + v~ w). Write its postfix expression. Also show steps to evaluate the postfix expression. Also show steps to evaluate the postfix expression using stack. (October 2018) Given: u=3,v=4,w=2 Solution ‘Steps | Symbol | Operator Stack | Postfix Expression Empty eee + u 3 - + uv 4 * uv 5 [w " uw [6 empty uwwe+ Step 1: Add u to postfix Step 2: Push operator + onto the top of the stack Step 3: Add v to postfix Step 4: Push operator « onto the stack, it has higher precedence then + Step 5: Add w to postfix Step 6: POP all operators from stack and add at the end of postfix expression. Postfix expression is uvwe+ Now. Evaluation of postfix where u =3, v=4, w= 2 Steps | Character | Stack | Operand 1 | Operand 2 | result 1 fu 3 = = = 2 \y 34 | = - 3 |w 34,2 |- = - 4 [38 [4 2 % 5 [+ nn [3 8 W Step 1: Push u =3 Step 2: Push v=4 Step 3: Push w =2 Step 4: Now operator is + So pop4 and 2 and perform multiplication, Result is 8. Then push 8. Step 5: Now operator is +. So pop 3 and 8 and perform addition, Result is 11. Then push I +. The final result is 11 S.Y. C-l Data Structures and Algo... . © Stack 5. Convert the infix expression: A|B$C+D*E-A*C to postfix notation show the stack contents. Solution Incoming | instack Output A - A 1 1 A 8 1 AB $ 1s AB c 18 ABC + + ABCS/ D + ABCS/D : + ABCSID E + ABCSIDE = - ABCS/DE"+ - ABCS/DE"+A . = ABCS/DE*+A c =| ABCS/DE*+AC 7 = __ | ABCSIDE*+AC~ 6. Give the output of the following sample code: initstack(s); push(s, 9); push(s, 4); 1 pop(s); while(! > 0) { push(s, | * 1); I-- } while(Istackempty(s)) printf("%d\n", pop(s)); Solution initstack push(s, 9) : wi (April 2018) (April 2018) O. S.Y.C:1Data Structures and Algo...¢ EJ + Stack wen 4 push(s, 4) i= pop(s); ied 8 while(4 > 0) 1 { 4 push (6, 1) Ins 16 } while(Istack empty(s)) i.e. Printf("%d\n", pop(s)); 7. Write a ‘C’ function to push and pop for stack using singly linked list. (October 2017) Solution void push(stack **T, char x) { stack *p; P = (stack *) malloc(sizeof(stack)); podata = xX; ponext = T; *T = py ) function pop() char pop(stack **T) ( char X; stack * p= *T; *T = ponext; X = podata; free(p); return (x); } S.Y. C-l Data Structures and Algo... + @ Stack whan 8. What are the applications of stack? (October 2017) Solution 2 Stack data structure is used in many applications, some of them are listed below: i. Conversion of infix to postfix and prefix expressions. ii. Evaluating the postfix expressions. iii, Reversing a list. iv. Recursion and subroutine calls. v. Checking correctness of nested parenthesis. vi. Parsing the computer program. vii. Decimal to binary conversion. viii. Back tracing algorithms. 9. Evaluate the following expression using stack: A+ B* C-D. (October 2017) Given data: A = 4,8 = 3,C =SandD=1. First convert expression to posttix. Solution A+B*C-D, A=4,B=3, C=SandD=1 Postfix expression A+B*C-D A+BC*-D ABC*+-D ABC*+D- Evaluation of postfix expression 1A a emeiec’ sian S.Y. C- Data Structures and Algo... © ofp = 18 10. Convert the following infix expression to posttix expression dle contents of stack at each step: (A +(B*C-(D/E*F)*G)*H) — (April 2017) Solution Input | Instack Output -|# = ( # = A | # A + ae A G #( AY EET A+B : #4 [A+B c [ac [A+B = [ac A+ BC ( #4 [A+BC* D_ | #-(__[A+BC*D i #4) | A+BC*D E #(-U_| A+BC* DE a #(/"_ | A+BC* DE Fo | «C(* [A+ BC* DEF ) #(—_ [A+BC*DEF*7 : a" [A+8C*DEF*/ G ("| A+BC*DEFA7G ) #( A+ BC*DEF*/G*— H # A+BC*DEF*7G*-H ) # A+BC*DEF*‘/G*-H Postfix expression: A + BC * DEF */G*—H O S.Y.C4 Data Structures and Algo...« [EE] + Stack niga Give the O/P of the following code: (April 2017) { inti = 1, x, ys 25 Initstack(; while(i < 3) { push(i* i); let41; 11. } x=pop(); y=pop(); push(i"!); z=popi(); push(x+y+z); push(x*y); while(!stackempty()) printt(“\n%d", pop()); ) Solution Output: 4 14 Explanation: while(i < 3) { push(i * i) ieitd; ) 1<3 True 7 2<3 Tue : 3<3 False x= pop); x=4 Y¥ = pop(); yal push(i* i) (i=3) @ Stack z=9 fal 4 14 S.Y. C-l Data Structures and Algo... # 2 = pop(): push (x + y +2) = 14 push(4) 12. Evaluate the postfix expression: xy +z - wu*/ where, x =7, y= 15,z=2,w=4,u=3 Solution The steps to evaluate any postfix expression are: E i. Scan the postfix expression from left to right. An operator is pushed on top of stack. back onto the stack. Final result is found on top of the stack (October 29 16) In case of an operator, two operands are popped from the stack, evaluated and Pushed Pond Input Stack Operand pean Value Comment 1 | xy+zwi/ | Empty : : -__| Initially + - . . | Push the operand onto the top eho: a of the stack : 7 . | Push the operand onto the top 3 +z-w'/ 715 eatieee . Perform the addition operation 7 1 ‘ ewe 2 : 22 | between 7 and 15 5 wut 22 2 - : - | Push the operand onto the top of the stack _| 6 wut 20 22 2 29 _ | Perform the subtraction Operation between 22 and 2 7 uy 204 : : . Push the operand onto the top. of the stack __ 8 " 2043 : : Push the operand onto the top of the stack __| 9 / 20 12 4 3 12 Perform the multiplication | operation between 4 and 3 10 Emy empty 20 12 1.6 | Perform the subtraction = " © | operation between 20 and 12_J S.Y. C-l Data Structures and Algo... ¢ W © Sta0k ke 13. Trace the output of the following: (October 2016) vold fun() { Int I=5, x, y, 2; Initstack(); whlle(I<8) { push(I+3); lel+1; } x=pop(); y=pop(); push(I+0); z=pop(); push(x+y+z); push(y+z); whlle(!stackempty()) printf(“\n%d”, pop()); } Solution The values of all the variables and the output of the given code is as follows: 1 |x |y | z | top | stack comment 5 | ! ! int in5, x, y, 2; | 5 -1 | empty initstack(); | 5 -1 | empty | while(i < 8) 5<8 5 0 |8 { push(i+3); 6 o|8 bl 15 6 0 |8 Againi<8 = 6<8 6 1/89 { push(i+3); [7 1/89 dni+1; ~ | . 2 FEE) «stack wsion S.Y. C-I Data Structures and Alg 7 1/89 Againi<8 7<8 7 2 |89 10 | { pushlir3); 8 2 |89 10 | iciet; 8 2/8910 | Againi<8 8<8 is false . 8 2 |8910 |) 8] 10 1 |89 10 | x=pop(); 8| 10/9 0 | 8910 | y=pop(); 8/10\9 1 | 8 8 10 | push(i+0); 8} 10/98] 0 |8 8 10 | z=pop(); 8/10/9/8| 1 | 8 27 10| push(xeysz); 8|10}9]8| 2 | 8 27 17] pushy+z); 8/10|9|8| 2 | 8 27 17| while(Istackempty()) 8/10}9/8) 2 | 8 27 17) printi(“1n%d", pop()); 8/10}9]8] 1 |827 | print17 e/10}9}s 8 print 17 print 27 8/10|9|8) 0 | empty | printe The output is 7 27 8 14, Write a C function to reverse a sentence using stack (Do not define any stack function). (April 2016) Solution Assume a sentence is accepted from user and push characters of the sentence on the stack. void reverse () { /*Pop characters from the sentence and store in string str */ for (i=0; i typedef struct node int info; S.Y. C-1 Data Structures and Algo... g * Queue struct node *next; } NODE; NODE *front, *rear; void initq() { front=rear=NULL; } int isempty() { return (front: } void addq(int num) { NODE *newnode; newnode=(NODE *)malloc (sizeof (NODE) ); newnode->info=num; newnode->next=NULL; if(front == NULL) rear=front=newnode; else { NULL) ; rear->next=newnode; rear=newnode; } int removeg() { int num; NODE *temp=front; num = front->info; front=front->next; free (temp) ; if (front==NULL) rear=NULL; return (num) ; } void main() { int choice, num; initqQ; do { printf("\n\nl : Add\n2 : Delete\n3 : Exit"); print£("\n\nenter your choice :"); scanf ("%d", &choice); switch (choice) { case 1: printf ("Enter the element scant ("$da", gnum) ; Ox vision ‘S.Y. C4 Data Structures and Algo... + addq (num) ; break; case 2 if (isempty ()) printf ("\nEmpty") ; else printf£("\nThe removed element is %d", removeq()); break; * Queue } } while (choice!=3); } 2. Write a‘ Solution #include #define MAXSIZE 5 typedef struct { int data (MAXSIZE]; int front , rear; } QUEUE; [OOOO ISHARES SPUNCTIONS SHE ERR void initq(QUEUE *pq) { pq->front = py->rear.= MAXSIZE-1; } int isempty (QUEUE *pq) { return (pq->front } int isfull (QUEUE *pq) { return ( (pq->rear+1) $MAXSIZE==pq->front) ; } void addq (QUEUE *pq, int num) { pq->rear= (pq->rear+1) MAXSIZE; Pq->data[pq->rear] = num; } int removeq(QUEUE *pq) { pq->front=(pq->front+1) $MAXSIZE; return pq->data(pq->front]; } void main() { Program to implement circular queue as an array. (October 2018) paq->rear); int n, choice; QUEUE ql; initq(&ql); do S.Y. C1 Data Structures and Algo... J ¢ Queue On printf ("\n1:ADD\n2:DELETE\n3:EXIT"); printf("\n\nEnter your choice :"); scanf ("&d", &choice) ; switch (choice) { case 1: /* ADD */ printf("\nEnter the element to be added :"); scanf ("%d", &n) ; if (isfull (&ql)) print£ ("Queue overflow "); else addq(&q1,n); break; case 2: /* DELETE */ if (isempty (éql)) printf£("\nQueue is empty \n"); else Printf£("The deleted element is $d", removeq(&ql)); break; ) } while(choice !=3); 3. Write a ‘C’ function to ADD and REMOVE elements from circular queue Implemented using array. (Apr. 2018, Oct. 2017) & Write a 'C' function for adding and deleting elements from a circular queue. (April 2017) Solution To add element void enqueue (queue *p, int x) { if (empty (p)) { Porear = p+front == 0; Podata = [prear]= x; } else { Porear = (porear + 1)% MAX; podata = [porear] = x; } } S.Y. C-l Data Structures and Algo... ¢ o Queue or To delete/remove element int dequeue (queue *p) { int x; x = podata = (p>front]; if(porear == p-front) initialize (p); else pofront = [pofront + 1]% MAX; return (x); } 4. Define Priority Queue. Explain Its types. (Apr. 2018, 2016) Solution A priority queue is a finite collection of elements where each element is assigned a priority. Following rules are applied to maintain a priority queue: 1. The elements with a higher priority is processed before any element of lower priority. 2. If there were elements with the same priority then the elements are processed according to the order in which they are added to the queue. Types of priority queue There are two types of priority queues 1. Max Priority Queue: In max priority queue, elements are inserted in the order in which they arrive the queue and always maximum priority value is removed first from the queue. For example, Assume that we insert element with priority 8, 3, 2, 5 and they are removed in the order 8, 5, 3, 2. The following are the operations performed in Max priority queue. a. _ isEmpty(): Check whether queue is empty. b. _insert(): Insert a new value into the queue. c. findMax(): Find maximum priority value in the queue. d. remove(): Delete maximum priority value from the queue. 2. Min Priority Queue: Min priority queue, is similar to max priority queue except removing maximum priority element first, we remove minimum priority element first in min priority queue. The following operations are performed in min priority queue. a. isEmpty(): Check whether queue is empty. b. insert(): Insert a new value into the queue. @ Queue S.Y. C-l Data Structures and Algo... @ c findMin(); Find minimum priority value in the queue. d. remove(): Delete minimum priority value from the queue. 5. Write a ‘C’ function to add and delete element from Linear Queue. (October 201; 6) Solution Queue is an ordered list of elements in which elements are inserted only at the end called as rear and elements are deleted only at the end called as front. Dynamic representation of Linear Queue as struct node int info; struct node *link; Me struct node *front, *rear; front = rear = NULL; The function to add an element in Linear Queue is as follows. This function has one parameter as data accepted from the user. void Add_Queue(int data) { struct node * tmp; tmp=(struct node *)malloc(sizeof(struct node)); //creation //node tmp->info = data; tmp->link = NULL; if (front == NULL) front = tmp; else rear->link = tmp; //assignment of link to the next node rear = tmp; 1 The function of deletion of an element from queue works on Queue strategy as FIFO (First In First Out) void Delete_Queue() 4 struct node * tmp; if (front NULL) printf ("Underflow"); S.Y. CI Data Structures and Algo... ¢ Cues, wis else { tmp =front; printf ("Deleted element is %d", tmp->info); front = front->link; free (tmp); 6. Consider a circular queue of characters of size 5. Initially queue contents are as follows: (April 2016) Front Rear Circular Queue 1 2 P/Q 01234 Show the value of front, rear and contents of queue for the following. i. addqueue(R) li. remove queue() iii. remove queue() iv. add queue(S) v. add queue(T) vi. add queue(U) vii. remove queue() viii. addqueue(V) Solution i. addqueue( R) Pla]R ii. remove queue() alr iii, remove queue() R iv. add queue(S) R|S v. add queue(T) T R[s| Queve . S.Y. C4 Data Structures and Algo. * vi. add queue(U) (rte Tals) vii. remove queue() fer rs] viii, add queue(V) 0 7 Jews) (2: VISION

You might also like