Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

--------------------------------------
Short Answer Questions
--------------------------------------

TOPIC : Introduction to Data Structure – Recursion and Garbage Collection


Q Define Data Structure? What are the different types of data structure?

In computer science, a data structure is a particular way of storing and organizing data in a computer so that it
can be used efficiently.
Generally data structure are of two types.
I) Linear – Array, linked list, stack, queue etc.
and II) Non-linear – tree, graph etc.

Q What is the difference between local variables and global variables?

Global variables once declared they can be used any where in the program i.e. even in many functions. If
possible we can use the global variables in the different user defined header files.
On the other hand global variables values can be changed programmatically.
local variables are local to a functional and cant be used beyond that function. These variables only exist
inside the specific function that creates them. They are unknown to other functions and to the main program.
As such, they are normally implemented using a stack. Local variables cease to exist once the function that
created them is completed. They are recreated each time a function is executed or called.

Q What is the difference between data and information?


Data
• Facts, statistics used for reference or analysis.
• Numbers, characters, symbols, images etc., which can be processed by a computer.
• Data must be interpreted, by a human or machine, to derive meaning
• Data is a representation of information
• Data plural, datum singular
Information
• Knowledge derived from study, experience (by the senses), or instruction.
• Communication of intelligence.
• Information is any kind of knowledge that is exchangeable amongst people, about things, facts, concepts, etc.,
in some context.
• Information is interpreted data

Q List the various operations performed on data structure?


•Traversing: Enables you to access the data elements of a data structure. For example, you can traverse all the
nodes of a tree.
•Inserting: Enables you to insert a data element in a data structure. For example you can insert a node in a
linked list.
•Deleting: Enables you to delete a data element from a data structure. For example, you can delete the last
element of a queue.
•Merging: Enables you to merge two or more data structures. For example, you can merge two linear arrays to
create a new array.
•Searching: Enables you to find the location of a data element in a data structure. For example, you can search the
location of a node in a tree.
•Sorting: Enables you to sort the data elements in a data structure in increasing or decreasing order. For example,
you can sort the element of a linear array in the increasing order.
•Updating: Enables you to update the changes made in a data structure. For example, first you can increase the
number of nodes in a tree and then update the number of nodes in the tree.

1
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

•Creating: Enables you to create a new data structure. For example, you can create a 2-D array containing 2s
rows and 5 columns.

Q Define Data Structure? What are the different types of data structure?
A data structure is a mechanism that you use for storing information. It determines interface that enables you to
add, delete, traverse, search and count the elements of structure. The data structures that you commonly use are
linked lists, stacks and queue. A linked list is a finite sequence of nodes, each of which contains a pointer field to
the next node. Stack is an ordered collection of elements that you can access only from end, called the top of
stack. Queue is an ordered collection of elements in which elements inserted from one end are deleted from
another end. The data structures are of two types linear and non-linear. Data structure is defined as a set of data
elements along with their operations that show the relationship among these data elements. You use data
structures for organising and storing the data in an ordered and controlled way. Various operations that you
perform on data structures are insertion, deletion, modification and traversal of the values present in these data
elements. An array stores a set of data elements that belongs to a single data type.

Q Define the big O notation?

In mathematics, computer science, and related fields, big O notation describes the limiting behavior of a
function when the argument tends towards a particular value or infinity, usually in terms of simpler functions.
Big O notation allows its users to simplify functions in order to concentrate on their growth rates: different
functions with the same growth rate may be represented using the same O notation.
Let f(x) and g(x) be two functions defined on some subset of the real numbers. One writes

if and only if, for sufficiently large values of x, f(x) is at most a constant times g(x) in absolute value. That is,
f(x) = O(g(x)) if and only if there exists a positive real number M and a real number x0 such that

Q Define pointer. How can you declare a pointer to a structure?

Pointer is an unsigned integer variable, which stores the address of an another variable.
In computer science, a pointer is a programming language data type whose value refers directly to (or "points
to") another value stored elsewhere in the computer memory using its address. A pointer references a value
stored elsewhere in memory, and obtaining or requesting the value to which a pointer refers is called
dereferencing the pointer.
Declaration of a pointer to a structure :
struct student {
int id;
char name [100];
struct student * next;
};

Q Define using example a void pointer?

Void pointer is a pointer variable, which does not hold the address of any variable. But after initialization it
can hold the address of any type of variable.
Example :
void * ptr;
int a=10;
ptr= &a;
Here ptr is void pointer and does not hold any address. But after initialization, ptr=&a, the pointer can hold the
address of an integer variable a.

Q What is recursion? What are its applications?

Recursion is the methodology in which a function or a method uses itself to complete a task. The concept of recursion is
mostly used in various languages such as C an; when you want to use a function more than once to perform a task.
For example, if you want to create a C program to calculate the factorial of an integer you can create a function, which

2
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

calculates the product of a number and one less than number. This function calculates the product of all the integers
ranging between, the number whose factorial is to be calculated.

TOPIC : Array and String

Q What is an array? How memory is allocated to arrays?

An array is a collection of homogeneous data type, stored in a contiguous memory location.

The elements of a linear array are stored at contiguous memory locations. We do not need to keep track of the
address of each data element of an array to perform any operation. We only need to know the base address of an
array. If we know the base address, you can calculate the memory location of any element of a linear array using the
formula:

Loc (LA [k]) = Base [LA] + w (k- lower bound)


Where
•LA: Specifies the linear array.
•K: Specifies the element whose location you want to find.
•Base: Specifies the base address of the linear array.
•W: Specifies the word length of the particular element.
•Lower bound: Specifies the starting index of the element.

The above figure shows the representation of memory for storing a linear array that stores integer values
starting from base address 101.

Q Write the syntax of multidimensional array of char.

The syntax of multidimensional array of char is : char arr_name[10][20], it means the name of the above array
is arr_name and it has 10 rows and 20 columns and 10x20 = 200 cells, and each cell contains a character, with
in it.

Q Write the application of pointer variable.

Some important applications of pointer variable :

• Dynamic memory allocation (Linked list)

3
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

• Storing linear or multidimensional array.


• Memory referencing in Operating System
• File handling.

TOPIC : Stack

Q What is a stack? What are the operations performed on stack?

In computer science, a stack is an abstract data type and data structure based on the principle of Last In First
Out (LIFO).A stack is an ordered list of items. Items are removed from this list in the reverse order to the
order of their addition. Any abstract data type can be an item or element of this list.
There are two operations, which can be performed on stack.

• Push ( ) - to insert an element in the stack.


• Pop ( ) - to delete an element from the stack.

Q Convert the following infix expressions into postfix expressions

i) (A-B)*(D/E)
ii) (A+B↑ D)/(E-F)+G
After conversion the expression will be as follows :
1. AB-DE/*
2. ABD^+EF-/G+

Q What is push operation of stack?

Push operation is used to insert an element in a stack at the end of it.


void push(int item)
{
top++;
stack[top] = item;
}
This operation makes a new index by increasing the value of top, and insert item(value) with in the stack, with that
index.

Q Write the prefix and postfix equivalent of the following infix expression: A * B+C.

Postfix expression equivalent to the given expression : AB*C+


Prefix expression equivalent to the given expression : +*ABC

Q When a stack is called underflow?

Stack Underflow is an error condition that occurs when an item is called for from the stack, but the stack is
empty. That means when a stack has no element with in it or it is empty, then if the pop() function is called,
then no element pulled out from the stack. And this situation is called stack underflow.

4
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Q Write four applications of Stacks.

The four application of stack is :


1. Recursion
2. Polish Notation
3. Tree traversing
4. Process control Block in OS

TOPIC : Queue

Q What is the difference between the stack and queue?

Stack is a Last In First Out (LIFO) data structure. But Queue is a First In First Out (FIFO) data structure.
Since both two operations insert and delete are made in the same place in stack, we have to use only one
pointer or counter to maintain the stack, But in the case of Queue we have maintain two pointers or counters.

Q What are queues? Give two examples of use of queues in computer system.

A queue is a particular kind of collection in which the entities in the collection are kept in order and the principal
(or only) operations on the collection are the addition of entities to the rear terminal position and removal of
entities from the front terminal position. This makes the queue a First-In-First-Out (FIFO) data structure.
Example of use of queues in computer system :
1. Process Scheduling – Ready Queue.
2. Critical Path Method in Graph.

Q What are priority queues?

A priority queue is an abstract data type in computer programming that supports the following three operations:
• Insert With Priority: add an element to the queue with an associated priority
• Get Next: remove the element from the queue that has the highest priority, and return it (also known as "Pop
Element(Off)", or "Get Minimum")
• Peek At Next (optional): look at the element with highest priority without removing it

Q What are the conditions for overflow and underflow for a Queue?

A practical implementation of a queue e.g. with pointers of course does have some capacity limit, that depends
on the concrete situation it is used in. For a data structure the executing computer will eventually run out of
memory, thus limiting the queue size. Queue overflow results from trying to add an element onto a full queue
and queue underflow happens when trying to remove an element from an empty queue.
Linked List

Q Define linked list?

In computer science, a linked list is data structure that consists of a sequence of data records such that in each
record there is a field that contains a reference (i.e., a link) to the next record in the sequence.

Q What is the difference between a linked list and an array?


OR Compare features of linked list & sequential list?

In linked list dynamic memory allocation takes place, but in array the memory allocation is static.
Linked list uses pointer to the next element, but array uses index to traverse the elements with in it.
In array memory wastage is possible, but in linked list memory wastage is not possible.
Memory overhead is less in implementing an array, but in linked list, the memory overhead is higher.

Q What are the advantages of doubly linked list?

A doubly linked list can be traversed in both directions (forward and backward). A singly linked list can only
be traversed in one direction.

5
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

A node on a doubly linked list may be deleted with little trouble, since we have pointers to the previous and
next nodes. A node on a singly linked list cannot be removed unless we have the pointer to its predecessor.
On the flip side however, a doubly linked list needs more operations while inserting or deleting and it needs
more space (to store the extra pointer).

Q What is the condition for the overflow in the linked lists?

Since linked list is based on dynamic memory allocation, often the overflow situation does not occur while
using linked list. But if the memory(Primary memory RAM) of the system is filled up while executing the
program, the overflow condition reached in linked list.

Q List any three applications of linked lists.

Applications of linked list :


1. Tree structure
2. Stack with linked list
3. Queue with linked list

Q Write advantages of a list over an array.

In linked list dynamic memory allocation takes place, but in array the memory allocation is static. So, we can
not allocate memory in run time, if we are using array. And hence the storage capacity can not be variable in
the case of array. But while using linked list, we can vary the storage, at the time of execution of the program.
Again, In array memory wastage is possible, but in linked list memory wastage is not possible.

Q If we always make insertions and deletions only at the start of a linked list, then which data structure it will
represent?

If we always make insertions and deletions only at the start of a linked list, then the data structure it will
represent is stack.

TOPIC : Tree & Graph

Q Write the various procedures of Tree traversal?


OR What are the three traversal techniques for Binary Trees? In what sequence the nodes are traversed in
them?

A tree can be traversed in three way generally.


1. Pre order traversal : traversing approach : Parent node → Left Child node → Right child node
2. Postorder traversal : traversing approach : Left Child node → Right child node → Parent node
3. In order traversal : traversing approach : Left Child node → Parent node → Right child node

Q Define complete binary tree?

A binary tree in which every level, except possibly the deepest, is completely filled. At depth n, the height of
the tree, all nodes must be as far left as possible.

Q What is heap?
In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if B is a
child node of A, then key(A) ≥ key(B). This implies that an element with the greatest key is always in the root
node, and so such a heap is sometimes called a max-heap. (Alternatively, if the comparison is reversed, the
smallest element is always in the root node, which results in a min-heap.)

6
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Q What are Binary Search trees?

In computer science, a binary search tree (BST) is a binary tree data structure
which has the following properties:
• Each node (item in the tree) has a distinct value.
• Both the left and right subtrees must also be binary search trees.
• The left subtree of a node contains only values less than the node's
value.
• The right subtree of a node contains only values greater than the
node's value.
The major advantage of binary search trees over other data structures is that
the related sorting algorithms and search algorithms such as in-order traversal
can be very efficient.

Q What are the characteristics of a binary tree?

We can determine some of the characteristics of binary trees


• A binary tree with internal nodes contains n+1 external nodes. This result is true regardless of the shape
of the tree. Consequently, we expect that the storage overhead of associated with the empty trees will be
O(n).
• A binary tree of height has at most internal nodes. Conversely, the height of a binary tree with n
internal nodes is at least . i.e., the height of a binary tree with n nodes is .
• A binary tree of height has at most leaves. Conversely, the height of a binary tree with l leaves is at
least . Thus, the height of a binary tree with l leaves is
Q Explain the terms used in trees : ordered tree, descendant, ancestor.

ORDERED TREE : A tree where the children of every node are ordered, that is, there is a first child, second
child, third child, etc.

TOPIC : Searching
Q What is the average complexity of binary search algorithm?

The average complexity of binary search is O(log n).

Q Consider the following list: 1, 5, 8, 12, 15. How many comparisons will you require using binary search
algorithm to find that 12 is at position 4 in the list.
1 5 8 12 15
beg mid end
Is value at mid = 12. No.
Is value at mid > 12
Is12 > value at mid=8? Yes. Then set beg=mid + 1
1 5 8 12 15
beg end

7
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

mid
mid=(beg+end)/2=(4+5)/2=9/2=4
Now is value at mid=12? Yes. Then search successful and location of 12 is mid=4.

Q Compare Linear & Binary searching techniques.

Binary search can be done on sorted array, but linear search can be done on any array.
Binary search runs in O(log n) time whereas linear search runs in O(n) times thus binary search has better
performance.
Binary search is most faster than linear search.

Q What are the conditions under which binary search is applicable?

Binary search can be done if the array is sorted. If we have to search an element from an unsorted array, with
the help of binary search, then we have sort the array first. On unsorted array the binary search can not be
performed.

Topic : Sorting
Q What are the complexities of
i) Insertions sort
ii) Merge sort

The average case time-complexity of insertion sort is O((N-1)*N/4), i.e. O(N2).


And The average case time-complexity of merge sort is O(n log n)

Q What is the average complexity of bubble-sort algorithm?

The average case time-complexity of insertion sort is O(N2).

Q What do you mean by the term “merging of two arrays”?

Merging of two arrays means to form one big array from two small arrays, which has element from both the
arrays linearly.
Ex. if we have the following two arrays:
array1 [5] = {1,2,3,4,5}
array2 [5] = {6,7,8,9,10}
and we merge these two arrays to form an array merge_array, then it would have these elements:
merge_array [5] ={1,2,3,4,5,6,7,8,9,10}
So, from this example we understand that the array which will hold the merged elements should have a
dimension equal to the sum of the dimensions of the two discrete arrays.

Q Give the average complexity of selection-sort and heap-sort algorithms.

The average complexity of selection sort is O(n2)


The average complexity of selection sort is O(n log n)

Q Write about straight selection sort.

One of the easiest sorting methods is selection sort. Beginning with the first element of the given array, a
search is made to find the largest element in the array. When the element is found this element is interchanged
with the last element of the array. Now the size of the unsorted array will be reduced but one. A search for the
largest element of the unsorted array is carried out. When this element is found it will be interchanged with the
last element of the unsorted array. Once again the unsorted array will be reduced by 1 and the above process
will be repeated till the entire array is sorted in ascending order.

8
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

--------------------------------------
Long Answer Questions
--------------------------------------

Topic : Introduction to Data Structure – Recursion and Garbage Collection


Q What are data structures? Explain any 5 data structures.
A data structure is a mechanism that you use for storing information. It determines interface that enables you to add,
delete, traverse, search and count the elements of structure. The data structures that you commonly use are linked lists,
stacks and queue. A linked list is a finite sequence of nodes, each of which contains a pointer field to the next node. Stack
is an ordered collection of elements that you can access only from end, called the top of stack. Queue is an ordered
collection of elements in which elements inserted from one end are deleted from another end. The data structures are of two
types linear and non-linear. Data structure is defined as a set of data elements along with their operations that show the
relationship among these data elements. You use data structures for organising and storing the data in an ordered and
controlled way. Various operations that you perform on data structures are insertion, deletion, modification and traversal
of the values present in these data elements. An array stores a set of data elements that belongs to a single data type.

An array is a data structure that stores a group of values belonging to the same data type. A data type is a classification of
data values that determine its type such as int, char and float. You can have an array that stores a group of characters,
integers or floats. The elements of an array are stored at successive memory locations and are accessed using an array
index. Various features of an array are:
• Array elements share the same name but are distinguished by an array index.
• Array elements are inserted or modified independently without disturbing other elements of the array.
• Array elements are easily assigned to a variable or an array variable of the same data type.
Arrays are categorized into different types based on the way it stores the elements:
• Linear arrays
• Multi-dimensional arrays
• Pointer arrays

Linked list is a linear collection of data elements called nodes that store a group of values belonging to the same data type.
The linked lists are known as dynamic data structures because the successive elements are not stored at contiguous memory
locations. The elements are stored at a location, whenever they find the free memory space. You can have a linked list that
stores a group of characters, integers or floats.

Each node is divided into two parts, data and link. The data part represents the value stored in the node and the link part
represents the address of the next node stored in succession. You can also have a node that contains two data fields and a link
field. The link field, also known as a pointer is used to provider linear order to the nodes. The syntax to declare a node in a
linked list is:

The above syntax shows how to declare a node in a linked list, struct is the keyword used for defining a linked list. The
variable, data holds the integer value stored in the node. The next filed is a link that holds the address of the next node in the
linked list.

A stack is a data structure, which is a set of ordered collection of data elements. The stack allows you to perform the
insertion and deletion of elements in a stack only from one end, called the top of stack. Stack implements the Last-in-
First-Out (LIFO) technique. The LIFO technique makes sure that only the top element is to be removed from the stack.
A pile of books is an example of a stack. Various applications of using stacks are:
•Reversing strings of characters.
•Evaluating algebraic expressions.
•Implementing function calls and recursion.
•Implementing game applications.
•Implementing the concept of recursive function calls

9
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Queue is a linear data structure, which is an ordered collection of data elements. A queue performs insertion of elements from
one end and deletion of the elements from the other end, whereas a stack performs insertion and deletion only from one end.
Queue implements the First-in-First-Out (FIFO) technique for insertion and deletion operations. The elements are inserted in
a queue from the rear end, also called the tail of queue. The deletion of elements is performed at the front end, also called the
head of queue. A queue of people waiting to deposit electricity bills is an example of a queue. The first person standing in a
queue is the first person to be served.

Trees are two-dimensional data structures that contain data elements arranged in hierarchical format. Unlike arrays and
linked lists, trees are non-linear structures. This is because in a tree data structure, each data element points to one or more
data elements.
Trees are used to store data that needs to be represented in a hierarchical format. For example, the file system of UNIX
operating system can be stored by usage of a tree data structure. Trees can also used to store mathematical expressions that
need to be evaluated by a language complier.
A tree or a basic tree is a finite set of one or more data elements that resembles an inverted real life tree where the root is at
top and the leaf nodes at the bottom. The root element branches out to one or more elements, which can further branch in a
similar way. The elements that do not branch out are called leaf elements. Figure 3.1 shows a tree data structure.

A Tree Data Structure


Q Write short note on:
(a) Algorithm complexity
(b) Space-time trade off

(a) Algorithm complexity

Algorithm complexity is the efficiency measure of an algorithm. For example, you can add first 20 natural
numbers using two methods. In the first method, you need to add the 20 numbers using general addition as:
Sum= 1 +2 + + 20
Sum= 210
Using the second method, you need to add the 20 numbers using the following formula:
Sum = (n * (n + l))/2
Here, n = 20, therefore sum of first 20 natural numbers is calculated as:
Sum = (20*(20+l)/2)
Sum = 210

You can see that the second way to calculate the sum of first 20 natural numbers is less complex and requires
less time to calculate in comparison of the first method. Therefore the algorithm complexity for the first way is
more than the second way.

(b) Space-time trade off

10
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Time space trade off is a situation in which you can reduce the computation time process by increasing the
memory. Time space trade off is mostly used in algorithms to run the algorithms in a fast manner. Time space
trade off is generally applied oz storage in the system.
For example, the data stored in uncompressed form takes more space as compared compressed data. However, the
uncompressed data takes less time to be accessed compared to compressed data.

Q Write short notes on:


(a) Dynamic storage management or Dynamic memory allocation
(b) Garbage collection.

(a) Dynamic storage management or Dynamic memory allocation

In computer science, dynamic memory allocation is the allocation of memory storage for use in a computer
program during the runtime of that program. It can be seen also as a way of distributing ownership of limited
memory resources among many pieces of data and code.
Dynamically allocated memory exists until it is released either explicitly by the programmer, exiting a block,
or by the garbage collector. This is in contrast to static memory allocation, which has a fixed duration. It is
said that an object so allocated has a dynamic lifetime.
Usually, memory is allocated from a large pool of unused memory area called the heap (also called the free
store). Since the precise location of the allocation is not known in advance, the memory is accessed indirectly,
usually via a reference.
For example, using linked list we can allocate the memory dynamically.

(b) Garbage collection

Garbage collection refers to searching the memory space, which is not used for a time and freeing that memory
space to allocate for another use. Garbage collection automatic memory management, which ensures that the
memory of a system is utilised appropriately. The various programming languages use garbage collection such
as Haskell and Lisp. Garbage collection results in fast execution of programs.

Topic : Array and String

Q Write steps to insert an element ITEM at location LOC(<n) in an array A[n], where n>0.

Insert(item, A[], LOC)


Step 1: Read item.
Step 2: set i =1.
Step 3: Repeat Step 4 while i < LOC
Step 4: i++
Step 5: set j=n-1
Step 6: Repeat Step 7 and 8 while j!=LOC
Step 7: A[j+1]=A[j]
Step 8: j++
Step 9: set a[i] = item
Step 10: Exit

Q Give different ways of inputting and outputting an array of number in terms of array and pointer notations.

Inputting and outputting an array of number in terms of array.

int a[50];
arr_input()
{
int n,i;
printf(“Enter the number of elements in array: ”);
scanf(“%d”,&n);
printf(“Enter the elements in array:\n”);
for(i=1;i<=n;i++)

11
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

{
scanf(“%d”,&a[i]);
}
}

arr_output()
{
int i;
printf(“The elements of the array is :\n”);
for(i=1;i<=n;i++)
{
printf(“%d\t”,a[i]);
}
}

Inputting and outputting an array of number in terms pointer notations.

int a[10];
int *ptr;
ptr=a;
ptr_input()
{
int n,i;
printf(“Enter the number of elements in array: ”);
scanf(“%d”,&n);
printf(“Enter the elements in array:\n”);
for(i=1;i<=n;i++)
{
scanf(“%d”,(ptr+i));
}
}

arr_output()
{
int i;
printf(“The elements of the array is :\n”);
for(i=1;i<=n;i++)
{
printf(“%d\t”,*(ptr+i));
}
}

Stack and Queues


Q Write the procedure to push and pop element in stack?
OR Write a set of routines for implementing several stacks within a single array.

12
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

In the above listing, the push() function inserts data elements in a stack. Also, a linear array, stack, with 10
data elements and an integer variable, top, with value, -1, are declared. The size of the stack array and the
value of the top variable will remain same in the complete program.

Q Convert the following infix expression into postfix expression showing the stack contents A+(B*C-
(D/E↑F)*G)*H

Given infix expression Maintained Stack Postfix expression as Output


A+(B*C-(D/E↑F)*G)*H NULL NULL
A+(B*C-(D/E↑F)*G)*H) NULL ( NULL
+(B*C-(D/E↑F)*G)*H) NULL( A
(B*C-(D/E↑F)*G)*H) NULL ( + A
B*C-(D/E↑F)*G)*H) NULL ( + ( A
*C-(D/E↑F)*G)*H) NULL ( + ( AB
C-(D/E↑F)*G)*H) Given infix expression Maintained Stack
-(D/E↑F)*G)*H) NULL ( + ( * ABC
(D/E↑F)*G)*H) NULL ( + ( - ABC*
D/E↑F)*G)*H) NULL ( + ( - ( ABC*
/E↑F)*G)*H) NULL ( + ( - ( ABC*D
E↑F)*G)*H) NULL ( + ( - ( / ABC*D
↑F)*G)*H) NULL ( + ( - ( / ABC*DE
F)*G)*H) NULL ( + ( - ( / ↑ ABC*DE
)*G)*H) NULL ( + ( - ( / ↑ ABC*DEF
*G)*H) NULL ( + ( - ABC*DEF↑/
G)*H) NULL ( + ( - * ABC*DEF↑/
)*H) NULL ( + ( - * ABC*DEF↑/G
*H) NULL ( + ABC*DEF↑/G*-
H) NULL ( + * ABC*DEF↑/G*-
) NULL ( + * ABC*DEF↑/G*-H
NULL NULL ABC*DEF↑/G*-H*+

Q Write algorithm to reverse a string using stack.

Input String is str[], output staring is result[] and we have to use the stack, stack[] to reverse the input string.
reverse()
Step 1: Read str[10].
Step 2: Set i = 0 and set top = 0.
Step 3: Repeat step 4 & step 5 while str[i] != '\0'
Step 4: push str[i] to stack[top]

13
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Step 5: i++ and top++


Step 6: Set j = 0
Step 7: Repeat step 8 & step 9 while top>=0
Step 8: set result [j] = stack[top]
Step 9: top-- and j++
Step 10: result[j]='\0'
Step 11: exit.

Q Write procedure to insert an element in a circular queue.

Q Use the infix to postfix conversion algorithm to convert an infix expression a+b*c/(e+f*g) to postfix
expression. Verify the result directly.

Given infix expression Maintained Stack Postfix expression as Output


a+b*c/(e+f*g) NULL NULL
a+b*c/(e+f*g) ) NULL ( NULL
+b*c/(e+f*g) ) NULL ( a
b*c/(e+f*g) ) NULL ( + a
*c/(e+f*g) ) NULL ( + ab
c/(e+f*g) ) NULL ( + * ab
/(e+f*g) ) NULL ( + * abc
(e+f*g) ) NULL ( + * / abc
e+f*g) ) NULL ( + * / ( abc
+f*g) ) NULL ( + * / ( abce
f*g) ) NULL ( + * / ( + abce
*g) ) NULL ( + * / ( + abcef
g) ) NULL ( + * / ( + * abcef
)) NULL ( + * / ( + * abcefg
) NULL ( + * / abcefg*+
NULL NULL abcefg*+/*+

Q What are the conditions, under which operations on stack can take place? What is LIFO?

The conditions, under which operations on stack can take place are
Stack overflow: It occurs when too much memory is used on the call stack. In many programming languages
the call stack contains a limited amount of memory, usually determined at the start of the program. The size of
the call stack depends on many factors, including the programming language, machine architecture, multi-
threading, and amount of available memory. When too much memory is used on the call stack the stack is said

14
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

to overflow; typically resulting in a program crash.


Stack Underflow: If a pop operation on the stack causes the stack pointer to move past the origin of the stack,
a stack underflow occurs.

LIFO: LIFO is an acronym which stands for last in, first out. In computer science and queueing theory this
refers to the way items stored in some types of data structures are processed. By definition, in a LIFO
structured linear list, elements can be added or taken off from only one end, called the "top". A LIFO structure
can be illustrated with the example of a narrow, crowded elevator with a small door. When the elevator
reaches its destination, the last people to get on have to be the first to get off.

Q Write the procedure to insert an item in a queue?

Q Write a set of routines for implementing several queues within a single array.

To implement queues with in an array, we have to introduce at least three procedures or routines.
i) INSERT()
ii) DELETE()
iii) DISPLAY()

Let us take the queue is Q[50] and there are two counters ins and del, both are integers and initially ins = -1,
del = 0.
Then the procedures are as follows:

INSERT()
{
int item;
if(ins > = 50)
{
printf(“Insertion not possible.”);
}
else
{
printf(“Enter intem to insert : ”);
scanf(“%d”,&item);
ins++;
Q[ins] = item;
printf(“DATA INSERTED”);
}
}

DELETE()
{

15
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

if(del>ins)
{
printf(“Deletion not possible.”);
}
else
{
del++;
}
}

DISPLAY()
{
int i;
printf(“The queue is :\n”);
for(i=del;i<=ins;i++)
{
printf(“%d\t”,Q[i]);
}
}

Q Write an algorithm to insert and delete an element from the circular queue.

16
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Linked List
Q Write the procedure to insert an item at the end of a linked list?

struct node
{
int data;
struct node * link;
}

Now we have to insert a value item at the end of the list.

insert(int item)
step 1: set ptr=start
step 2: create a new node struct node newnode
step 3: set newnode → link = NULL and newnode → data = item.
step 4: if start = NULL
step 5: set start = newnode
step 6: else repeat step 7 while ptr → link != NULL
step 7: ptr = ptr → link
step 8: set ptr → link = newnode
step 9: End of if
step 10: return

Q Explain the two way list? List the various operations performed on two way list?

17
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

In computer science, a doubly-linked list or two way ,inked list is a linked data structure that consists of a set
of data records, each having two special link fields that contain references to the previous and to the next
record in the sequence. It can be viewed as two singly-linked lists formed from the same data items, in two
opposite orders.

A doubly-linked list whose nodes contain three fields: an integer value, the link to the next node, and the link
to the previous node.
The two links allow walking along the list in either direction with equal ease. Compared to a singly-linked list,
modifying a doubly-linked list usually requires changing more pointers, but is sometimes simpler because
there is no need to keep track of the address of the previous node.

Inserting a node
These symmetric functions add a node either after or before a given node, with the diagram demonstrating
after:

function insertAfter(List list, Node node, Node newNode)


newNode.prev := node
newNode.next := node.next
if node.next = null
list.lastNode := newNode
else
node.next.prev := newNode
node.next := newNode

function insertBefore(List list, Node node, Node newNode)


newNode.prev := node.prev
newNode.next := node
if node.prev is null
list.firstNode := newNode
else
node.prev.next := newNode
node.prev := newNode

We also need a function to insert a node at the beginning of a possibly-empty list:


function insertBeginning(List list, Node newNode)
if list.firstNode = null
list.firstNode := newNode
list.lastNode := newNode
newNode.prev := null
newNode.next := null
else
insertBefore(list, list.firstNode, newNode)

A symmetric function inserts at the end:


function insertEnd(List list, Node newNode)
if list.lastNode = null
insertBeginning(list, newNode)
else
insertAfter(list, list.lastNode, newNode)

Deleting a node

Removing a node is easier, only requiring care with the firstNode and lastNode:
function remove(List list, Node node)
if node.prev = null
list.firstNode := node.next

18
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

else
node.prev.next := node.next
if node.next = null
list.lastNode := node.prev
else
node.next.prev := node.prev
destroy node

Q Write a program to show all the operation on linked list.


OR Write a procedure to search an element from a linked list.
OR Write steps to delete an element from a linked list.
OR Explain the algorithm to insert a new node after a target node in the linked list.
OR Write a program or give an algorithm to delete a node from the beginning of the linked list.

In the above listing, the insert_end() function inserts a node at the end of the singly linked list.

In the above listing, the insert_mid() function insets a new node after any other node in the singly linked list.

19
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

In the above listing, the delete_node() function deletes a desired node in the singly linked list

In the above listing, the traverse() function displays all the nodes in the singly linked list.

In the above listing, the count() function counts the number of nodes present in the singly linked list.

20
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

In the above listing, the search() function searches a node value in the singly linked list and returns the result in the
list.

The above listing the main() function and enables you to enter a choice to perform various operations on the singly
linked list.

21
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

22
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

The above listing accepts the user choice and calls various functions, which are defined earlier.

The above listing shows how to implement a singly linked list. It shows how to insert a node at the beginning, middle
or at the end of a list and how to perform deletion, traversal, count and search operations on a singly linked list. Figure
below shows the output of Listing 2.13.

Q Give recursive & non-recursive algorithm of counting the number of nodes in a linked list.

The recursive algorithm of counting the number of nodes in a linked list.

count = 0;
ptr = first;
while (ptr != NULL) {
count ++;
ptr = ptr->next;
}

The non-recursive algorithm of counting the number of nodes in a linked list.

int count(ptr)

23
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

{
int res=1;
if (ptr != NULL)
{
ptr=ptr → link;
res=1+count(ptr);
}
else
{
res=1;
}
return res;
}

Q Write a C function to traverse a circular-linked list visited every node.

TOPIC : Tree & Graph

Q Describe different types of binary tree?

Types of Binary Trees

Binary tree are of three types and this categorisation is done based on the number of child nodes of each node and the
depth at which the nodes exist. The various types of binary trees are:
l Strictly l Complete l Extended

Strictly Binary Trees

Strictly binary trees are the binary trees whose each node contains zero or two child nodes. A strictly binary tree with
N leaf nodes contains 2N-1 child nodes. Figure below shows a strictly binary tree.

24
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Complete Binary Trees

Complete binary trees are strictly binary trees in which all leaf nodes are at the same depth. A complete binary tree
with M nodes at level L can contain 2 M nodes at level L+1. Therefore, a complete binary tree of depth D contains 2D
nodes. Figure below shows a complete binary tree.

Extended Binary Trees

In an extended binary tree, the special nodes are added to a binary tree to make it a complete binary tree. For example,
an incomplete binary tree contains nine nodes: A, B, C, D, E, F, G, G and I. Figure below shows a binary tree with the
nodes.

To make it a complete binary tree, you need to add four special nodes, S1, S2, S3 and S4, as the child nodes of the
nodes C, D, E and F. After adding four special anodes, binary tree becomes and extended binary tree. Figure below

25
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

show the extended binary tree that included special nodes, S1, S2, S3 and S4.

Q What is the difference between binary search tree and heap? Build a heap H from the following data 44, 30,
50, 22, 60, 55, 77, 55. Show diagram of each insertion?

In a heap, a nodes key is greater than equal to both of its children's keys. In binary search tree, a node's key is
greater than or equal to its child's key but less than or equal to right child's key. Furthermore, this applies to
entire subtree in the binary search tree case. It is very important to note that the heap property does not help
print the nodes in sorted order because this property does not tell us in which subtree the next item is. If the
heap property could used to print the keys (as we have shown above) in sorted order in O(n) time, this would
contradict our known lower bound on comparison sorting.
The last statement implies that since sorting n elements takes Ω(n lg n) time in the worst case in the
comparison model, any comparison-based algorithm for constructing a Binary Search Tree from arbitrary list
n elements takes Ω(n lg n) time in the worst case.
We can show the validity of this argument (in case you are thinking of beating Ω(n lg n) bound) as follows: let
c(n) be the worst-case running time for constructing a binary tree of a set of n elements. Given an n-node
BST, the in order walk in the tree outputs the keys in sorted order (shown above). Since the worst-case
running time of any computation based sorting algorithm is Ω(n lg n) , we have
c(n) + O(n) = Ω(n lgn)
Therefore, c(n) = Ω(n lgn).

26
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Q Discuss the various representations of tree in memory? Explain the merits and demerits of each?

REPRESENTING BINARY TREES USING ARRAYS

A binary tree can be represented using arrays in which nodes are numbered from 0 to n. The left child of a node is
positioned at the 2n + 1 array position, and the right child of a node is positioned at 2n + 2.
Figure below shows the way in which nodes of a tree are numbered and placed at various array positions. The node P is
numbered 0, followed by Q and W as the 1st and 2nd nodes. The 3rd node is empty and S is the fourth node.
Representation of binary trees using arrays is sequential in nature since arrays are sequential structures. The array
elements are allocated memory even if a child exists or not. The empty array element positions are marked as unused and
the ones that occupy data are marked used. The requirement of marking an element as used or unused can be fulfilled by
defining a structure that can store data element and the used/unused node information about the data elements.

27
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

REPRESENTING BINARY TREES USING LINKED LISTS

Binary trees can also be represented using linked lists. Unlike representation using arrays, linked list representation is non-
sequential. This is because each node of a linked list can point-to two other nodes and they in turn can point to any two nodes
and so on. The representation involves defining a structure for a node that consists of a:
• Pointer to the left node
• Pointer to the right node
• Variable of any data type to store information

A node has two pointers, one pointing to the left child and the other to the right child. As a result, each node has the same
structure as that of a doubly linked list node. The code to define the structure of a node is:

struct node
{
char data;
struct node * left;
struct node * right;
}

Q Draw the binary tree corresponding to following traversal sequences:

In order : D B F E A G C L J H K
Postorder : D F E B G L J K H C A

28
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Q Construct the binary search tree if the following elements are inserted in it in the given sequence: 14 45 16
22 12 65 43 33 18 30

29
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Q What are the steps to delete a node in BST? Explain with the help of an example.

30
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

TOPIC : Searching

Q Write the program for binary search?


OR Explain binary search algorithm in details.

Q Give any two differences between linear and binary search algorithm. What are the limitations of binary
search?

In a linear search, each data item is checked one by one in the order in which it exists in the structure to determine if it

31
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

matches the criteria of search. A binary search involves comparison of the search data with the data at the centre of the
list and then a comparison with the elements in the first half or second half of the list.

The syntax for linear search is:

The syntax for binary search is:

Q Compare index sequential search and binary search. Which one has a maximum search efficiency?

Binary Search Indexed Sequential Search


It follows the divide and conquer algorithm. It follows linear search algorithm.
It is one tire searching. It is two tire Searching.
The complexity of Binary Search is less than Indexed The complexity of Indexed Sequential Search is less than
Sequential Search. the complexity of binary search.
Here the Searched elements must be sorted. Here the searched elements must be indexed.
It is used for single dimensional array. It is used for multi dimensional array.

Indexed sequential search has the maximum search efficiency. Because it is an two tire searching. So, for indexed
sequential searching, there is no need to search the entire data elements. This searching technique is used to search the
index of the data to be searched.

TOPIC : Sorting
Q Explain the difference between quick sort and heap sort?

Heap sort is a much more efficient version of selection sort. It also works by determining the largest (or smallest)
element of the list, placing that at the end (or beginning) of the list, then continuing with the rest of the list, but
accomplishes this task efficiently by using a data structure called a heap, a special type of binary tree. Once the data
list has been made into a heap, the root node is guaranteed to be the largest element. When it is removed and placed at
the end of the list, the heap is rearranged so the largest element remaining moves to the root. Using the heap, finding
the next largest element takes O(log n) time, instead of O(n) for a linear scan as in simple selection sort. This allows
Heap sort to run in O(n log n) time.

On other hand, Quick sort is a divide and conquer algorithm which relies on a partition operation: to partition an array,
we choose an element, called a pivot, move all smaller elements before the pivot, and move all greater elements after
it. This can be done efficiently in linear time and in-place. We then recursively sort the lesser and greater sublists.
Efficient implementations of quicksort (with in-place partitioning) are typically unstable sorts and somewhat complex,
but are among the fastest sorting algorithms in practice. Together with its modest O(log n) space usage, this makes
quicksort one of the most popular sorting algorithms, available in many standard libraries. The most complex issue in
quick sort is choosing a good pivot element; consistently poor choices of pivots can result in drastically slower (O(n²))
performance, but if at each step we choose the median as the pivot then it works in O(n log n).

32
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

Q What is bubble sort technique? Apply this on the following list of numbers 44, 33, 11, 55, 77, 90, 40

Bubble sort is a straightforward and simplistic method of sorting data that is used in computer science education. The
algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the
second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts
again with the first two elements, repeating until no swaps have occurred on the last pass. While simple, this algorithm
is highly inefficient and is rarely used except in education. A slightly better variant, cocktail sort, works by inverting
the ordering criteria and the pass direction on alternating passes. Its average case and worst case are both O(n²).
Applying bubble sort on given array:

44 33 11 55 77 90 40
→ 44 → 33 11 55 77 90 40
33 → 44 → 11 55 77 90 40
33 11 → 44 → 55 77 90 40
33 11 44 → 55 → 77 90 40
33 11 44 55 → 77 → 90 40
33 11 44 55 77 → 90 → 40
33 11 44 55 77 40 90 ←
sorted
Max element

→ 33 → 11 44 55 77 40 90
11 → 33 → 44 55 77 40 90
11 33 → 44 → 55 77 40 90
11 33 44 → 55 → 77 40 90
11 33 44 55 → 77 → 40 90
11 33 44 55 40 → 77 → 90
11 33 44 55 40 77 ← 90

→ 11 → 33 44 55 40 77 90
11 → 33 → 44 55 40 77 90
11 33 → 44 → 55 40 77 90
11 33 44 → 55 → 40 77 90
11 33 44 40 55 ← 77 90

→ 11 → 33 44 40 55 77 90
11 → 33 → 44 40 55 77 90
11 33 → 44 → 40 55 77 90
11 33 40 44 ← 55 77 90

11 33 40 44 55 77 90

Array sorted.

Q Apply Quick Sort algorithm to sort following elements:


4, 13,15, 7, 25, 19, 20, 22, 28, 39

A: 4 13 15 7 25 19 20 22 28 39
Selecting 19 as pivot for array A and split the A array into two arrays B and C.

B pivot(A) C
4 13 15 7 19 20 22 28 39 25
Selecting 13 as pivot for array B and split the B array into two arrays D and E.

D pivot(B) E pivot(A) C
4 7 13 15 19 20 22 28 39 25
Selecting 28 as pivot for array C and split the C array into two arrays F and G.

33
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

D pivot(B) E pivot(A) F pivot(C) G:


4 7 13 15 19 20 22 25 28 39

Sorted B = D + pivot(B) + E pivot (A) Sorted C = F + pivot(C) + G


4 7 13 15 19 20 22 25 28 39
Sorted A = Sorted B + pivot(A) + Sorted(C)
4 7 13 15 19 20 22 25 28 39

The array is sorted

Q Write about the followings and compare : insertion sort and selection sort.

Selection sort

Selection sort is a simple sorting algorithm that improves on the performance of bubble sort. It works by first
finding the smallest element using a linear scan and swapping it into the first position in the list, then finding
the second smallest element by scanning the remaining elements, and so on. Selection sort is unique compared
to almost any other algorithm in that its running time is not affected by the prior ordering of the list: it
performs the same number of operations because of its simple structure. Selection sort also requires only n
swaps, and hence just Θ(n) memory writes, which is optimal for any sorting algorithm. Thus it can be very
attractive if writes are the most expensive operation, but otherwise selection sort will usually be outperformed
by insertion sort or the more complicated algorithms.

Insertion sort

Insertion sort is a simple sorting algorithm that is relatively efficient for small lists and mostly-sorted lists, and
often is used as part of more sophisticated algorithms. It works by taking elements from the list one by one
and inserting them in their correct position into a new sorted list. In arrays, the new list and the remaining
elements can share the array's space, but insertion is expensive, requiring shifting all following elements over
by one. The insertion sort works just like its name suggests - it inserts each item into its proper place in the
final list. The simplest implementation of this requires two list structures - the source list and the list into
which sorted items are inserted. To save memory, most implementations use an in-place sort that works by
moving the current item past the already sorted items and repeatedly swapping it with the preceding item until
it is in place. Shell sort (see below) is a variant of insertion sort that is more efficient for larger lists. This
method is much more efficient than the bubble sort, though it has more constraints.

Q Write a program for sorting of n numbers.


OR Write an algorithm/program to implement selection sort.

#include<stdio.h>
#include<conio.h>
void main(void)
{
int n,i,j,t,a[50];
clrscr();
printf(“Enter the number of elements in array: ”);
scanf(“%d”,&n);
printf(“Enter the elements in array:\n”);
for(i=1;i<=n;i++)
{
scanf(“%d”,&a[i]);
}
//sorting started
for(i=1; i<n; i++)
{
for(j=i+1; j<=n; j++)
{
if(a[i]>a[j])

34
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf(“The array is sorted and the sorted array is : \n”);
for(i=1;i<=n;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}

Q Write a program or give an algorithm to implement quick-sort algorithm.

Q Give insertion-sort algorithm and write down its average complexity.

35
Data Structure : BCA 204/ BSCIT 202/ MCA 302/ MSCIT 103

36

You might also like