0% found this document useful (0 votes)
123 views22 pages

Dsa Answers

The document discusses different operations that can be performed on data structures: 1. Create - Reserving memory for program elements using functions like malloc(). 2. Destroy - Destroying allocated memory space using functions like free(). 3. Selection - Accessing a particular data item. 4. Updation - Modifying data. 5. Searching - Finding a data item by conditions. 6. Sorting - Arranging data in order like ascending or descending. 7. Merging - Combining sorted lists. 8. Splitting - Partitioning a list into multiple lists. 9. Traversal - Systematically visiting each node.

Uploaded by

anmol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views22 pages

Dsa Answers

The document discusses different operations that can be performed on data structures: 1. Create - Reserving memory for program elements using functions like malloc(). 2. Destroy - Destroying allocated memory space using functions like free(). 3. Selection - Accessing a particular data item. 4. Updation - Modifying data. 5. Searching - Finding a data item by conditions. 6. Sorting - Arranging data in order like ascending or descending. 7. Merging - Combining sorted lists. 8. Splitting - Partitioning a list into multiple lists. 9. Traversal - Systematically visiting each node.

Uploaded by

anmol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

2-mark questions

1. Explain the different operations to be performed on data structures.

Operation on Data Structures


Design of efficient data structure must take operations to be performed on the
data structures into account. The most commonly used operations on data
structure are broadly categorized into following types

1. Create:- The create operation results in reserving memory for program


elements. This can be done by declaration statement. Creation of data
structure may take place either during compile-time or run-time.
malloc() function of C language is used for creation.
2. Destroy:- Destroy operation destroys memory space allocated for
specified data structure. free() function of C language is used to destroy
data structure.
3. Selection:- Selection operation deals with accessing a particular data
within a data structure.
4. Updation:- It updates or modifies the data in the data structure.
5. Searching:- It finds the presence of desired data item in the list of data
items, it may also find the locations of all elements that satisfy certain
conditions.
6. Sorting:- Sorting is a process of arranging all data items in a data
structure in a particular order, say for example, either in ascending
order or in descending order.
7. Merging:- Merging is a process of combining the data items of two
different sorted list into a single sorted list.
8. Splitting:- Splitting is a process of partitioning single list to multiple list.
9. Traversal:- Traversal is a process of visiting each and every node of a
list in systematic manner.
2. What is the difference between Array and Linked list?
3. Evaluate the address of 5th index element in 1-D array if base address is 600 and
the data stored needs 3bytes of storage.

4. Each element of an array A[-20……….20, 10…….35] requires one byte of storage.


If the array is column major implemented & beginning of array is at location 500,
Determine the address of element at A[0][30].

Row Major System:


The address of a location in row major system

Address of A[i][j]=B+W*[N*(i-Lr)+(j-Lc)]

Column Major System :

Address of a location in Column Major System

Address of A[i][j] Column Major wise=B+W*[(i-Lr)+M*(j-Lc)]

rows(M)= (Ur-Lr)+1

column(N)=(Uc-Lc)+1

Base address B = 500


Element size W = 1 byte
M (number of rows) are 20 – (-20) +1 = 41
N (number of columns) are 35 – 10 + 1 = 26
Lr = -20 ; Lc = 10 ; i = 0 ; j = 20
Address of A[0][20] = 500 + 1(0-(-20)+41(20-10))]
                              = 500 + 1(20 + 41 x 10)
                              = 500 + (20+410)
                              = 500 + (430)
                              = 930.

5. What is ADT?
An ADT is a mathematical model of a data structure that specifies the type of data
stored, the operations supported on them, and the types of parameters of the
operations.
6. Define polish notation with an example.

Polish Notation is a general form of expressing mathematical, logical and


algebraic equations. The compiler uses this notation in order to evaluate
mathematical expressions depending on the order of operations. There are
in general three types of Notations used while parsing Mathematical
expressions:

● Infix Notation

● Prefix Notation

● Postfix Notation

The operators are placed left for every pair of operands. So, for the above
Infix X+Y, its equivalent Polish or Prefix Notation is +XY
7. Describe all type of linked list

A linked list is a linear data structure, in which the elements are not stored at
contiguous memory locations. The elements in a linked list are linked
using pointers. In simple words, a linked list consists of nodes where each
node contains a data field and a reference(link) to the next node in the list. 
Types Of Linked List 
● Singly Linked List: It is the simplest type of linked list in which
every node contains some data and a pointer to the next node of
the same data type. The node contains a pointer to the next node
means that the node stores the address of the next node in the
sequence. A single linked list allows traversal of data only in one
way. Below is the image for the same:

● Doubly Linked List: A doubly linked list or a two-way linked list is


a more complex type of linked list which contains a pointer to the
next as well as the previous node in sequence, Therefore, it
contains three parts are data, a pointer to the next node, and a
pointer to the previous node. This would enable us to traverse the
list in the backward direction as well. Below is the image for the
same:

● Circular Linked List: A circular linked list is that in which the last
node contains the pointer to the first node of the list. While
traversing a circular liked list, we can begin at any node and
traverse the list in any direction forward and backward until we
reach the same node we started. Thus, a circular linked list has no
beginning and no end. Below is the image for the same:

5-mark questions
1. What is data structure? Classify data structure in its different types and explain
them with the help of diagram? Also, Explain time and space trade-off .

A data structure is a collection of data type ‘values’ which are stored and
organized in such a way that it allows for efficient access and
modification. In some cases a data structure can become the underlying
implementation for a particular data type.

1. Array
Data stored in each position of an array is given a positive value called the
index of the element. The index helps in identifying the location of the
elements in an array.
2. Stack

The data structure follows the rule of LIFO (Last In-First Out) where the data
last added element is removed first. Push operation is used for adding an
element of data on a stack and the pop operation is used for deleting the
data from the stack. This can be explained by the example of books stacked
together. In order to access the last book, all the books placed on top of the
last book have to be safely removed.

3. Queue
This structure is almost similar to the stack as the data is stored
sequentially. The difference is that the queue data structure follows FIFO
which is the rule of First In-First Out where the first added element is to exit
the queue first. Front and rear are the two terms to be used in a queue.
Enqueue is the insertion operation and dequeue is the deletion operation.
The former is performed at the end of the queue and the latter is performed
at the start end.

4. Linked List
Linked lists are the types where the data is stored in the form of nodes
which consist of an element of data and a pointer. The use of the pointer is
that it points or directs to the node which is next to the element in the
sequence. The data stored in a linked list might be of any form, strings,
numbers, or characters. Both sorted and unsorted data can be stored in a
linked list along with unique or duplicate elements.

5. Hash Tables
These types can be implemented as linear or non-linear data structures.
The data structures consist of key-value pairs.

6(1). Trees
A tree data structure consists of various nodes linked together. The
structure of a tree is hierarchical that forms a relationship like that of the
parent and a child. The structure of the tree is formed in a way that there is
one connection for every parent-child node relationship. Only one path
should exist between the root to a node in the tree. Various types of trees
are present based on their structures like AVL tree, binary tree, binary
search tree, etc.

6(2). Graph
Graphs are those types of non-linear data structures which consist of a
definite quantity of vertices and edges. The vertices or the nodes are
involved in storing data and the edges show the vertices relationship. The
difference between a graph to a tree is that in a graph there are no specific
rules for the connection of nodes. Real-life problems like social networks,
telephone networks, etc. can be represented through the graphs. 
A space–time or time–memory trade-off in computer science is a case where an algorithm or
program trades increased space usage with decreased time. Here, space refers to the data
storage consumed in performing a given task, and time refers to the time consumed in
performing a given task.

2. Apply the row major order formula to calculate the address of element at X[4,3] in
a 2D array X[1..5][1..4] stored in a row major order. Assume base address=1000
and each element requires 4 words of storage.
Address of row major A[i][j]=B+W*[N*(i-Lr)+(j-Lc)]

Base address B = 1000


Element size W = 4 byte
M (number of rows) are 5 – 1+1 = 5
N (number of columns) are 4 – 1 + 1= 4
Lr = 1 ; Lc = 1 ; i = 4 ; j = 3
Address of X[4][3] = 1000 + 4(4*(4-1)+(3-1))
                              = 1000 + 56
                              = 1056

3. Consider the following infix expression:


A+(B*C-(D/E^F)*G)*H
Transform this expression into Postfix expression using stack.
1. Explain recursion with the help of an example.
What is Recursion? 
The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called as recursive function. 
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
    int n;
    printf("Enter a positive integer: ");
    scanf("%d",&n);
    printf("Factorial of %d = %ld", n, multiplyNumbers(n));
    return 0;
}

long int multiplyNumbers(int n) {
    if (n>=1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}

2. Each element of an array Data[20][50] requires 4 Bytes of storage. Base address of data is
2000. Determine the location of Data[10][10], when the array is stored as
i) Row major
ii) Column major

Base address B = 2000 

Element width w = 4 bytes 

Total rows  m =  20-1+1=20

Total columns n = 50-1+1=50

ARR[I][J] = ARR[10]10]  => I = 10, J = 10

Lowest row index Lr = 0

Lowest column index Lc = 0

(i) Row wise  

DATA[I][J] = B + w(n(I – Lr) + (J – Lc)) 

DATA [10][10] = 2000 + 4(50(10-0) + (10-0)) = 2000 + 2040 = 4040

(ii) Column wise 

DATA [I][J]=B+W((I-Lr)+M(J-Lc) )

DATA [10][10] = 2000 + 4((10-0) + 20(10-0)) = 2000 + 840 = 2840
Note: This answer maybe wrong

3. Consider the linear arrays AAA[ 5:50], BBB[-5:10] and CCC[18].


i) Find the number of elements in each array.
ii) Suppose base address(AAA)=300 and w=4 words per memory cell for
AAA. Find the address of AAA[15], AAA[35] and AAA[55].

Consider the linear arrays AAA[5:50], BBB [-5:10] and CCC[1:8].

(a) Find the number of elements in each array

(b) Suppose Base(AAA) = 300 and w=4 words per memory cell for AAA. Find the address of
AAA[35] ,AAA[15], and AAA[55]

(a) Length = Upper Bound – Lower Bound +1


Length(AAA) = 50-5+1 = 46
Length(BBB) = 10-(-5)+1 = 16
Length(CCC) = 18-1+1 = 18

(b) Using the formula: LOC(AAA[k]) = Base(AAA)+w(K-LB)


LOC(AAA[15] )= 300+4(15-5) = 340
LOC(AAA[35] )= 300+4(35-5) = 420
AAA[55] is not an element of AAA since 55 exceeds UB = 50.

4. Suppose the following stack of integers is in memory where STACK is allocated N = 6


memory cells
TOP = 3 STACK: 5, 2, 3, _, _, _ ;
Find the output of the following program segments

1. Call POP (STACK, itemA) 🡪 STACK: 5, 2, _, _, _, _ ;


Call POP (STACK, itemB) 🡪 STACK: 5, _, _, _, _, _ ;
Call PUSH (STACK, itemB+2) 🡪 STACK: 5, 2, _, _, _, _ ;
Call PUSH (STACK,8) 🡪 STACK: 5, 2, 8, _, _, _ ;
Call PUSH (STACK, itemA + itemB) 🡪 STACK: 5, 2, 8, 7, _, _ ;
FINAL - STACK: 5, 2, 8, 7, _, _ ;

2. repeat while TOP <>0


call POP (STACK, item)
print “ item”

Stack : 0,0,0,0,_,_; (2nd part May be wrong)

8 Marks Questions
1. Write the applications of stack. Explain how can you reverse a string using stack with the
help of an example. Also write a C function for this.

Following is the various Applications of Stack in Data Structure:


o Evaluation of Arithmetic Expressions
o Backtracking
o Delimiter Checking
o Reverse a Data
o Processing Function Calls

We can use this method or operation to revers a string value.

*create an empty stack


*one by one push all characters of string to stack
*one by one pop all characters from stack and put them back to string.

#include <stdio.h>
#include <string.h>

#define max 100
int top, stack[max];

void push(char x)
{

    // Push(Inserting Element in stack) operation
    if (top == max - 1)
    {
        printf("stack overflow");
    }
    else
    {
        stack[++top] = x;
    }
}

void pop()
{
    // Pop (Removing element from stack)
    printf("%c", stack[top--]);
}

int main()
{
    char str[] = "kaisa ho bhaiyo behno || hue hue hue";
    int len = strlen(str);
    int i;

    for (i = 0; i < len; i++)
        push(str[i]);

    for (i = 0; i < len; i++)
        pop();
    return 0;
}
2. What is singly linked list? What all operations can be applied on SLL? Write algorithm to
perform insertion and deletion operation on SLL.

A singly linked list is a type of linked list that is unidirectional, that is, it can be
traversed in only one direction from head to the last node (tail).

Operations on Single Linked List


The following operations are performed on a Single Linked List

● Insertion
● Deletion
● Display

Insertion
In a single linked list, the insertion operation can be performed in three ways. They are as
follows...

1. Inserting At Beginning of the list


2. Inserting At End of the list
3. Inserting At Specific location in the list

Inserting At Beginning of the list


We can use the following steps to insert a new node at beginning of the single linked list...

● Step 1 - Create a newNode with given value.

● Step 2 - Check whether list is Empty (head == NULL)

● Step 3 - If it is Empty then, set newNode→next = NULL and head = newNode.

● Step 4 - If it is Not Empty then,


set newNode→next = head and head = newNode.

Inserting At End of the list


We can use the following steps to insert a new node at end of the single linked list...

● Step 1 - Create a newNode with given value and newNode → next as NULL.

● Step 2 - Check whether list is Empty (head == NULL).

● Step 3 - If it is Empty then, set head = newNode.

● Step 4 - If it is Not Empty then, define a node pointer temp and initialize


with head.
● Step 5 - Keep moving the temp to its next node until it reaches to the last node in
the list (until temp → next is equal to NULL).

● Step 6 - Set temp → next = newNode.

Inserting At Specific location in the list (After a Node)


We can use the following steps to insert a new node after a node in the single linked list...

● Step 1 - Create a newNode with given value.

● Step 2 - Check whether list is Empty (head == NULL)

● Step 3 - If it is Empty then, set newNode → next = NULL and head = newNode.

● Step 4 - If it is Not Empty then, define a node pointer temp and initialize


with head.

● Step 5 - Keep moving the temp to its next node until it reaches to the node after
which we want to insert the newNode (until temp1 → data is equal to location,
here location is the node value after which we want to insert the newNode).

● Step 6 - Every time check whether temp is reached to last node or not. If it is


reached to last node then display 'Given node is not found in the list!!!
Insertion not possible!!!' and terminate the function. Otherwise move
the temp to next node.

● Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp →


next = newNode'

Deletion
In a single linked list, the deletion operation can be performed in three ways. They are as
follows...

1. Deleting from Beginning of the list


2. Deleting from End of the list
3. Deleting a Specific Node

Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the single linked list...

● Step 1 - Check whether list is Empty (head == NULL)

● Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and


terminate the function.

● Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize


with head.

● Step 4 - Check whether list is having only one node (temp → next == NULL)
● Step 5 - If it is TRUE then set head = NULL and delete temp (Setting Empty list
conditions)

● Step 6 - If it is FALSE then set head = temp → next, and delete temp.

Deleting from End of the list


We can use the following steps to delete a node from end of the single linked list...

● Step 1 - Check whether list is Empty (head == NULL)

● Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and


terminate the function.

● Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and


'temp2' and initialize 'temp1' with head.

● Step 4 - Check whether list has only one Node (temp1 → next == NULL)

● Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate the


function. (Setting Empty list condition)

● Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next
node. Repeat the same until it reaches to the last node in the list. (until temp1 →
next == NULL)

● Step 7 - Finally, Set temp2 → next = NULL and delete temp1.

Deleting a Specific Node from the list


We can use the following steps to delete a specific node from the single linked list...

● Step 1 - Check whether list is Empty (head == NULL)

● Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and


terminate the function.

● Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2'


and initialize 'temp1' with head.

● Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or


to the last node. And every time set 'temp2 = temp1' before moving the 'temp1'
to its next node.

● Step 5 - If it is reached to the last node then display 'Given node not found in the
list! Deletion not possible!!!'. And terminate the function.

● Step 6 - If it is reached to the exact node which we want to delete, then check
whether list is having only one node or not

● Step 7 - If list has only one node and that is the node to be deleted, then
set head = NULL and delete temp1 (free(temp1)).

● Step 8 - If list contains multiple nodes, then check whether temp1 is the first node
in the list (temp1 == head).

● Step 9 - If temp1 is the first node then move the head to the next node (head =
head → next) and delete temp1.

● Step 10 - If temp1 is not first node then check whether it is last node in the list
(temp1 → next == NULL).

● Step 11 - If temp1 is last node then set temp2 → next = NULL and


delete temp1 (free(temp1)).

● Step 12 - If temp1 is not first node and not last node then set temp2 →
next = temp1 → next and delete temp1 (free(temp1)).

3. Write the algorithm to evaluate a postfix expression. Write the steps to evaluate this
expression:
20 8 4 / 2 3 + * -

Algorithm to evaluate the postfix expression

1.      Create a stack to store operands.

2.      Scan the given expression from left to right.

3.      a)     If the scanned character is an operand, push it into the stack.

b)        If the scanned character is an operator, POP 2 operands from stack and perform
operation and PUSH the result back to the stack.

4.      Repeat step 3 till all the characters are scanned.

5.      When the expression is ended, the number in the stack is the final result.

4. Give array implementation of stack data structure. Write functions to implement PUSH and
POP operations on stack.
Stack Operations using Array
A stack can be implemented using array as follows...

Before implementing actual operations, first follow the below steps to create an empty
stack.

● Step 1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.

● Step 2 - Declare all the functions used in stack implementation.

● Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])

● Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)

● Step 5 - In main method, display menu with list of operations and make suitable
function calls to perform operation selected by the user on the stack.

Implementation of Stack using Array
#include <stdio.h>
#include <conio.h>

#define SIZE 10

    void
    push(int);
void pop();
void display();

int stack[SIZE], top = -1;

void main()
{
    int value, choice;
    clrscr();
    while (1)
    {
        printf("\n\n***** MENU *****\n");
        printf("1. Push\n2. Pop\n3. Display\n4. Exit");
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            printf("Enter the value to be insert: ");
            scanf("%d", &value);
            push(value);
            break;
        case 2:
            pop();
            break;
        case 3:
            display();
            break;
        case 4:
            exit(0);
        default:
            printf("\nWrong selection!!! Try again!!!");
        }
    }
}
void push(int value)
{
    if (top == SIZE - 1)
        printf("\nStack is Full!!! Insertion is not possible!!!");
    else
    {
        top++;
        stack[top] = value;
        printf("\nInsertion success!!!");
    }
}
void pop()
{
    if (top == -1)
        printf("\nStack is Empty!!! Deletion is not possible!!!");
    else
    {
        printf("\nDeleted : %d", stack[top]);
        top--;
    }
}
void display()
{
    if (top == -1)
        printf("\nStack is Empty!!!");
    else
    {
        int i;
        printf("\nStack elements are:\n");
        for (i = top; i >= 0; i--)
            printf("%d\n", stack[i]);
    }
}

5. Using algorithm convert the given infix expression into postfix expression.
a) ( A + B * C / D – E + F / G / ( H + I ) )
b) A * ( B + D ) / E – F * ( G + H / K )
a

You might also like