The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Aditya Diwan, 2024-03-13 06:55:17

Data Structure Question and Answer

Data Structure Question and Answer

Unit 1 Chapter -4 Multi-Dimensional Arrays Question & Answer: - Ques1: - Define Multi-Dimensional Arrays Ans: A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays (meaning it is a matrix of rows and columns). A 3D array adds another dimension, turning it into an array of arrays of arrays. Ques2: - Explain the different memory representation of two-dimensional arrays with an example. Ans: ROW MAJOR REPRESENTATION In this representation the arrays are stored in the memory in terms of the row design, i.e. first the first row of the array is stored in the memory then second and so on. Suppose we have an array named arr having 3 rows and 3 columns then it can be stored in the memory in the following manner:


int arr[3][3]; In this representation 1 st row is stored from the base address then 2nd row is stored then 3rd row is stored and so on. Location of A[i,f]with Size=RowSize(m) x ColSize(n) can be calculated using following mapping function. Case 1: Index started from 0,0 Location[i,j]= Base Address(A)+{(i*ColSize)+j}*Word Size) Case 2: Index started from 1,1 Location[i,j]= Base Address(A)+[{(I-1)*ColSize}+ (j-1)]*Word Size) Where WordSize is the size of the data type. For example, for integer it would be either 2 or 4 COLUMN MAJOR REPRESENTATION In this representation the arrays are stored in the memory in the term of the column design, i.e. the first column of the array is stored in the memory then the second and so on. By taking above eg. we can show it as follows:


Assume that the matrix is collection of columns. In this mapping scheme 1st column is stored from the base address then 2nd column is stored then 3rd column is stored and so on. Location of A[i,j] with Size = RowSize(m) x ColSize(n) can be calculated using following mapping functions. Case 1: Index started from 0,0 Location[i,j]= Base Address(A)+{i+(j*RowSize)}*Word Size) Case 2: Index started from 1,1 Location[i,j]= Base Address(A)+[(i-1)+{(j-1)*RowSize}]*WordSize) Ques3: Explain the difference between Row major Vs Column major memory representation. Ans: Row-Major Representation: Storage Pattern: • In row-major order, the elements of each row are stored together in contiguous memory locations. • Rows are stored one after another, and elements within the same row are stored consecutively. 2.Memory Access Formula: The formula to calculate the memory location of an element at position (i, j) in row-major order is calculated using the formula: address = base_address + (i * number_of_columns + j) * size_of_each_element Usage: Commonly used in languages like C and C++ for representing multi-dimensional arrays. Example: For a 3x4 matrix: 1 2 3 4 5 6 7 8 9 10 11 12


The elements would be stored in memory as ‘1 2 3 4 5 6 7 8 9 10 11’. Column-Major Representation: Storage Pattern: • In column-major order, the elements of each column are stored consecutively in memory. • Columns are stored one after another in contiguous memory locations. Memory Access Formula: The memory location of an element at position (i, j) in column-major order is calculated using the formula: address = base_address + (j * number_of_rows + i) * size_of_each_element Usage: Commonly used in languages like Fortran and in some mathematical and scientific computing environments. Example: For the same 3x4 matrix: 1 5 9 2 6 10 3 7 11 4 8 12 The elements would be stored in memory as ‘1 5 9 2 6 10 3 7 11 4 8 12’. Ques4: - Write an algorithm to find the addition of two matrices. Ans: Algorithm Matrix Addition (A, B, M, N, X, Y) Here A is a two-dimensional array with M rows and N columns and B is a two-dimensional array with X rows and Y columns. This algorithm adds these two arrays. 1. If (M ≠ X) or (N ≠ Y) Then 2. Print: Addition is not possible. 3. Exit [End of If] 4. Repeat For I = 1 to M


5. Repeat For J = 1 to N 6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit Ques5: - Write an algorithm to find the subtraction of two matrices. Ans: Matrix Subtraction (A, B, M, N, X, Y) Here A is a two-dimensional array with M rows and N columns and B is a two-dimensional array with X rows and Y columns. This algorithm adds these two arrays. 1. If (M ≠ X) or (N ≠ Y) Then 2. Print: Subtraction is not possible. 3. Exit [End of If] 4. Repeat For I = 1 to M 5. Repeat For J = 1 to N 6. Set C[I][J] = A[I][J] - 8[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit Ques6: - Write an algorithm to find the multiplication of two matrices. Ans: Matrix Multiplication (A, B, M, N, X, Y) 1. If (M ≠ Y) or (N ≠ X) Then 2. Print: Multiplication is not possible. 3. Else 4. Repeat For I = 1 to N 5. Repeat For J = 1 to X 6. Set C[I][J] = 0


7. Repeat For K = 1 to Y 8. Set C[I][J] = C[I][J] + A[I][J] ≠ B[I][J] [End of Step 7 For Loop] [End of Step 5 For Loop] [End of Step 4 For Loop] [End of If] 9.Exit Ques7: - Write a C Program to find the addition and subtraction of matrices. Ans:


Ques8: - Write a C Program to find the multiplication of two matrices. Ans:


Ques9: - What is sparse matrix? What is transpose of sparse matrix? Explain with an example. Ans: SPARSE MATRIX Matrices which contain high numbers of zero entries are called sparse matrices. In simple terms, matrix which contain more zero elements than non-zero elements are referred as sparse matrix. TRANSPOSE OF A MATRIX The transpose of a matrix is a new matrix that is obtained by exchanging the rows and columns. Transposing a Sparse Matrix: To transpose a sparse matrix, for each row of the sparse matrix<I,j,value> and store it in the element <j,I,value> of the transpose as shown below.


Ques10: - Write a program to check whether matrix is sparse matrix or not. Ans:


Ques11: - Write a program to find the transpose of sparse matrix. Ans: Created By: - Assigned By: - Sumit Debbarma Mr. Aditya Diwan Sir Deep Raj Gupta Suman Das Rohit Roy


Unit 2 Chapter- 5 Linked Lists


Unit 2 Chapter- 5 Linked Lists Question and Answers: - Ques1: What do you understand by a Linked list? Ans: A linked List, in simple terms, is a linear collection of data elements. These data elements are called nodes. Ques2: what are the advantages and disadvantages of linked lists over arrays. Ans: ➢ Advantages of Linked Lists over Arrays • Efficient Memory Utilization. • Insertion and Deletion operations are Easier and Efficient. • Extensive Manipulations. • No Memory Wastage. • Arbitrary Memory Locations. ➢ Disadvantages of Linked List Over Arrays • Extra Memory Space. • Random Access. • Traversal and Search Time. Ques3: How Linked list is represented using an array? Explain with example. Ans:


Ques4: Explain the dynamic representation of linked list. Ans: • The process of allocating memory at runtime is known as dynamic memory allocation. • The functions malloc() and calloc() are used to allocate memory and free() is used to deallocate memory. • In dynamic representation of linked list, a node is created dynamically whenever it is required. Any number of nodes can be created depending upon the requirement. • The link member field contained in that structure node, which is used to point to the same structure type is called self-referential structure. • There is no need to setup any actual storage space at this stage as space will be allocated for each node as needed when the program is running. In order to create a linked list structure is to declare that defines all the list entries. The above structure is capable of holding the data plus the address of the memory space holding the next structure in this list. A node may contain any number of information fields. The general syntax for this is: Node Struct node { Int info: struct node * link; }; Struct node { Int info1, info2, info3,………info6; Struct node * link; };


Info1 Info2 Info3 Info4 Info5 Info6 Link Ques5: write a C- function to create a singly linked list with an example. Ans: Ques6: write a note on getnode() and freenode() operations. Ans: ➢ Getnode() • The first area where the allocation of dynamic memory space to the node during the program execution is done by means an operation called getnode. • Getnode is used only for building a node. It never breaks down the node. • if we go on creating the nodes using getnode, the number of nodes that can be possibly used will reduce. • Whenever a getnode is invoked, a newnode is created different from all the nodes previously in use.


p.t.o ➢ Freenode() • to reuse an operation is used known as freenode. • This operation makes it possible to make a node that is no longer being used in its current context available fore reusing it in different context. • The freenode() operation adds a node to the front of availability list. Ques7: Explain Garbage Collection. Ans: Garbage is a block of heap memory that cannot be accessed by the program. OR Garbage collection [GC] is an automatic management of dynamically allocated storage. It reclaims unused heap bocks for later use by program. • Garbage collection is a form of automatic memory management. • The garbage collector attempts to reclaim garbage or memory occupied by the objects or pointers that are no longer in use by a program. • Garbage collection is opposite of manual memory management, which requires the programmer to specify which object to deallocate and return to the memory system. • Garbage collection may take a significant proportion of total processing time in a program and can thus have significant influence on performance. • Resources other than memory, such as network sockets, database handles, user interaction windows etc. are not handled by garbage collection. • The basic principles of garbage collection are: • Finds data objects in a program that cannot be accessed in the future. • Reclaim the resources used by those objects.


Ques8: What is List as ADT? Ans: A list is a sequence of zero or more elements of a given type. Consider the list A1, A2, A3,…. An. The ADT list is a linear sequence of an arbitrary number of items, together with the following properties and operations. Let us assume that the list has the following properties. • The size of the list is N. • Ai-1 precedes of Ai. • The position of Ai is i. • The items in the list must have of the same type. • The empty list has size 0. • Ai follows Ai-1. Operations on list: 1. createList() : creates an empty list. 2. add(index, item) : insert item at position index of a list. 3. isEmpty() : Determine if a list is empty. 4. size() : Returns number of items in a list. 5. remove(index) : Remove item at position index of a list. 6. traverse() : Traverse all the elements in the list. 7. sort() : Sort the elements in the list. 8. search() : Searching an element in the list. Ques9: How memory is allocated for a node in Linked List? Explain with an example. Ans: There are two ways to allocate memory for a node. 1. Static representation using array. 2. Dynamic representation using free pool of storage. • Static representation Static representation of single linked list maintains two arrays: one array for information and the other for the Links or pointers as INFO[] and LINK[]. These two arrays should be of equal size and


parallel to each other. The memory size of these arrays should be sufficient to store the entire linked list. • Dynamic representation of linked list The process of allocating memory at runtime is known as dynamic memory allocation. The functions malloc() and calloc() are used to allocate memory and free is used to deallocate memory. Info1 Info2 Info3 Info4 Info5 Info6 Info7 Link Ques10: Mention the types of linked list. Ans: Types of linked list: • Singly linked list. • Doubly linked list. • Circular linked list. • Header linked list. Ques11: Mention the operations on linked list. Ans: Operations on linked list 1. Creation. 4. Searching. 7. Sorting. 2. Traversing/ Display. 5. Inserting. 8. Merging 3. Length. 6. Deletion. 9. Reversing.


Ques12: Write C-function or algorithm to find the length of singly linked list. Ans: C- function: int length() { int len = 0; NODE *CURRPTR; if (start == NULL) { Printf(“The linked list is empty \n”); Return(len); } CURRPTR = start; while (CURRPTR != NULL) { len++ ; CURRPTR = CURRPTR -> LINK; } return(len); } Ques13: Write a C- function or algorithm to search an item X in a linked list. Ans: Algorithm: Step 1: set CURRPTR = start, LOC = NULL Step 2: Repeat step 3 while CURRPTR ≠ NULL Step 3: if (ITEM == INFO [CURRPTR] ) then LOC = CURRPTR and display “search successful” EXIT else CURRPTR = LINK[CURRPTR] [so CURRPTR, now points to the next node] Step 4: if LOC = NULL display “search unsuccessful” Step 5: EXIT


Ques14: Write a C function or algorithm to i. Insert an item at the beginning of the singly linked list (S.L.L) ii. Insert an item at the end of the S.L.L iii. Insert an item at the specified position. iv. Insert an item into the sorted linked list. Ans: i. Insert an item at the beginning of the singly linked list (S.L.L) Function:


ii. Insert an item at the end of the S.L.L


iii. Insert an item at the specified position iv. Inserted an item into a sorted linked list Step 1: If the list is empty, then make the new node as head. Step 2: If the new node value is lesser than the head node, then insert it at the start, make it the head. Step 3: Traverse through the list until the data of the next of current is less than the data of the new node. By doing this, we are looking for an appropriate position to insert the new node. Step 4: When the loop breaks, insert the new node just after the current node: 1) New_node – > next = current – > next 2) current – > next = New_node


Ques15: Write a C-function or algorithm to 1. Delete an item from the beginning of S.L.L C-function: P.T.O


2. Delete an item from the end of S.L.L. C-function:


3. Delete an item from the specified position of S.L.L. C-function:


Ques16: What is linked list? With the aid of algorithms discuss how a node can be inserted and deleted from such a list. Ans: A linked list is a sequence of nodes in which each node contains on or more data fields and a pointer to the next node. A node can be inserted in many ways


A node can be deleted in many ways:


Ques17: Write a C- program to implement insert and delete operations on S.L.L. Ans: C- Program to implement insert operations on S.L.L.


P.T.O C-Program to implement delete operations on S.L.L. P.T.O


Ques18: Write a C- function or algorithm to display the contents of singly linked list. Ans: Algorithm: C- Program:


Ques19: What is circular list? What are the advantages of circular linked lists over singly linked list. Ans: A circular linked list is a type of linked list in which the last node of the list points back to the first node, forming a circle or loop. In other words, the last next pointer of the last node in the list is not NULL; instead, it points to the first node. This arrangement creates a closed loop, allowing traversal though the entire list from any starting point. Advantages of Circular List: • The circular list can be traversed to any node from any node. • All the nodes link address will have valid addresses, instead of NULL pointer. • A node can be inserted at or deleted from any position of the linked list. • One can start at any node in the list and traverse the whole list. Ques20: What do you mean by header node? Explain the types of header linked list. Ans: A header linked list is a linked list which always a info contains a special node called header node at the beginning of the list. The info field of such a header node generally contains the global information of the entire list. There are two kinds of widely used header linked list: • Grounded header linked list 1. The grounded header linked list is also referred as ‘singly header linked list’. In this the last node LINK field contains the NULL pointer.


2. Here, the info field of header node contains the number of nodes in a linked list (excluding header list). 3. The number of nodes in the list may be obtained directly from the header node without traversing the entire list. 4. The info field of header node contains the address of last node. • Circular header linked list 1. A linked list in which last node points to the header node is called circular header linked list. 2. Here, the info field of header node is containing the number of nodes in a linked list(excluding header node). 3. The length of a linked list can be obtained from the info of the header node. 4. The info value of header node should be incremented and whenever we delete a node from the linked list, the info value of header node should be decremented. Ques21: Mention the advantages and disadvantages of header linked list. Ans: • Advantages 1. Simplified Operations. 2. Improved list management. 3. Facilities empty list handling.


4. Simplifies algorithms. • Disadvantages 1. Wasted memory. 2. Complex initialization. 3. Potential for confusion. 4. Increased code complexity. Ques22: What do you mean by doubly linked list? What are the advantages and disadvantages of doubly linked list? Ans: A doubly linked list is a data structure in which each nodes holds a data element and had two pointers- one pointing to the previous node and another pointing to the next node in the sequence. • Advantages 1. The doubly linked list can be traversed in forward or backward direction. 2. If any particular node address is known, one can have both successor node address and predecessor node address that makes inserting and deleting much easier. 3. The doubly linked list is used to represent the trees effectively. 4. This simplifies list management. • Disadvantages 1. Extra memory is required to store the back pointer. Ques23: Write a C- function to search an item in singly linked list. If the item is found, then return true, else add the item at the beginning of the list and return false. Ans: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> // Define the Node structure struct Node { int data; struct Node* next; }; P.T.O // Function to create a new node


struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; return newNode; } // Function to search for an item in a singly linked list bool searchAndInsert(struct Node** head, int item) { struct Node* current = *head; struct Node* newNode; // Search for the item in the list while (current != NULL) { if (current->data == item) { // Item found, return true return true; } current = current->next; } // Item not found, insert at the beginning newNode = createNode(item); newNode->next = *head; *head = newNode; // Return false return false; } // Function to display a singly linked list void displayList(struct Node* head) { struct Node* current = head; while (current != NULL) { printf("%d -> ", current->data); current = current->next; } printf("NULL\n"); }


int main() { struct Node* head = NULL; // Example: Search for item 3, then display the list if (searchAndInsert(&head, 3)) { printf("Item 3 found in the list.\n"); } else { printf("Item 3 not found. Added at the beginning.\n"); } // Display the list after the operation displayList(head); return 0; } Ques24: Write a program to add two polynomials using linked list. Ans: P.T.O


Ques25: Write a program to add elements into ordered linked list and perform delete operations on ordered linked list. Ans: P.T.O


Ques26: What is Dynamic Memory Allocation? Ans: Dynamic memory allocation refers to the process of allocating memory for variable or data structures during the runtime of a program. It allows a program to request memory from the system while the program is running, rather than relying on fixed, static memory allocations defined at compile-time. Ques27: What is Dynamic Data Structure? Ans: A dynamic data structure is a way of organizing and storing data in a program that allows for flexibility in size and structure during the execution of the program. Unlike static data structures, which have fixed sizes determined at compile-time, dynamic data structures can change in size and shape as needed while the programming is running. Ques28: Explain Dynamic Memory Allocations Functions in C with an example. Ans: 1. malloc() malloc is used for dynamic memory allocation and is useful when you don’t know the amount of memory needed during compile time. Allocating memory allows objects to exist beyond the scope of the current block. 2. calloc() It is used to allocate a specified amount of memory and then initialize it to zero. The function returns a void pointer to this memory location, which can then be cast to the desired type. The function takes in two parameters that collectively specify the amount of memory to be allocated. 3. Free() The free() function is used to deallocate memory that was allocated using the malloc() or calloc() functions. It takes pointer to the memory block to be freed as its only argument. The memory block is then returned to the system and can be reused by other programs. Created By: - Assigned By: - Sumit Debbarma Mr. Aditya Diwan Sir Deep Raj Gupta Suman Das Rohit Roy


UNIT-2 CHAPTER-5 Stacks


UNIT-2 CHAPTER-5 Stacks Questions & Answers: - Ques1: Define a stack. Explain the working of a stack with a suitable example. Ans: A stack is a collection of homogeneous data items where the insertion and deletion take place at one end in a LIFO (Last in First out) fashion. This end is termed as TOP of the stack The insertion and deletion operations that can be performed on the stacks are technically termed as PUSH and POP respectively Ques2: Write Push and Pop algorithm Ans: Algorithm to push an element in a stack 1: [overflow check] If TOP = MAXSTK-1 Then write (‘Stack overflow’)


2: [Increment TOP value] TOP = TOP+1 3: [Insert the item at the TOP] S[TOP] = item 4: return Explanation Overflow occurs whenever an extra item is attempted to push in to stack even after TOP reached MAXSTK-1. So, Top should always be less than MAXSTK in order to prevent overflow problems. If TOP is equal to MAXSTK-1, then ‘stack overflow’ is to be displayed else TOP should be incremented by ‘1’ and the item is pushed into the stack. So, S[TOP] now becomes the new item. Algorithm to pop an element from a stack 1: [Underflow check] If TOP = -1 Then write (‘Stack underflow on POP’) And exit () 2: [Delete the item] Item = S[TOP] 3: [Decrement TOP value] TOP = TOP-1 4: exit () Explanation We know that underflow occurs whenever an item is tried to pop from the empty stacks. So, TOP should not be equal to -1. If TOP is equal to -1, then ‘Stack Underflow on POP’ is to be displayed else the item is to be popped (deleted) from the stack. Step2 indicates the deletion


of an item from the top of the stack. After deleting an item TOP should be decremented by 1. Ques3: Write C program for PUSH and POP operations of a stack implemented using arrays. The functions should check overflow and underflow conditions. Ans:


Ques4: How a stack can be represented using Arrays? Ans: Since stack is also a collection of same type of items, we can take array for implementing a stack. It is easy to implement but the problem here is we have to allocate the memory block of sufficient size prior to the operation. It is usually suggested to declare the array to be large enough without wasting too much memory space. Associated with each stack there is a top item of the stack, on which the PUSH and POP operations are to be performed. For this we need to consider a variable TOP which keeps the position of the top item in the stack. This variable TOP is set to ‘-1’ for an empty stack. As the Array size is already declared, it may be possible that sometimes there can not be the place for an item to be pushed (added). This condition is termed as ‘stack overflow’. For this, we need to check the value of TOP with the size of the array prior to the operation. Sometimes it may be possible that there is no item in the stack to POP (delete). If there is no element in the stack, the TOP value will be ‘-1’. This condition of popping from an Empty stack is termed as ‘stack underflow’. For this, we need to always check the value of TOP before deleting the item. Ques5: How a stack can be represented using Linked List? Ans: In a linked stack, every node has two parts- one that stores data and another that stores the address of the next node. The START pointer of the linked list is used as TOP. All the insertions and deletions are done at the node pointed by TOP. If TOP=NULL, then it indicates that the stack is empty


Ques6: Explain Stack as ADT Ans: A stack is a first in last out (FILO) structure, or a last in first out (LIFO) structure. A stack is sometimes generalized with insertion(push) and removal(pop) all at same end. A stack is either empty or consists of two parts, a top element and stack (the remaining elements). The elements in a stack may be of any type, but all the elements in a given stack must be the same type. A good example of stack is a stack of dishes in the dining hall. We cannot get the one on bottom unless we pick up all the ones on top of it. Ques7: Mention the operations on stack Ans: Push (): - Insert an element at the TOP of the stack Pop (): - Deleting an element from the TOP of the stack Isempty (): - Checks whether the stack contains any item and displays true if it is empty Stacktop (): - To determine what the TOP item on a stack list is, without removing it. Display (): - Used to display the elements of the stack


Click to View FlipBook Version