You are on page 1of 52

Question Bank

Class: S.Y. B. Sc (Computer Science)


Subject: Data Structures and Algorithms-I
Prepared By: Mrs. Galande C.S
Chapter 1.
Introduction to Data Structures and Algorithm Analysis
I. Multiple choice questions
1. An algorithm which takes linear time over all inputs is --------
a) Logarithmic. b) Quadratic c) Constant d) Linear.
2. In which algorithm running time doubles as input value added in set of input
a)Exponential algorithm. b) Linear c) Constant d) Cubic.
3. Which time complexity gives an upper bound on time requirements?
a) Best case b) worst case c) Average case d) none of above
10. The function used to calculate best case time complexity of an algorithm.
a) O b) Ω c) Ө d) o
4. If for an algorithm time complexity is given by O(1) then complexity of it is:
a) Constant. b) Polynomial. c) Exponential. d) Factorial.
5. If for an algorithm time complexity is given by O(log2n) then complexity will:
a)Constant. b) Polynomial. c) Exponential. d) Factorial.
ANSWERS:
1-c, 2-a, 3-c, 4-b, 5-a, 6.d

II. Fill In The Blanks:


1. ----------- is a set of domain D, a designated set of domains d € D, a set of functions F and
a set of Axioms A.
2. A ------- data is non decomposable entity.
3. A data structure in which elements are stored in consecutive memory locations is
-------------- data structure.
4. A ------------ data structure uses one-to-many relationship.
5. An algorithm which takes direct squared size of input performance time over all inputs is
called ----------- algorithm.
6. An algorithm whose running time is bounded by polynomial expression over all inputs is
called ----------- algorithm.
Answers:
1)Data Structure 2) automic 3)sequential 4)non linear 5)Quadratic
6)polynomial
III. State TRUE or FALSE.
1. Data is raw information that has been translated into a form which is efficient for
processing.
2. A data structure in which size of structure remains fixed is dynamic data structure.
3. The function f(n) = Ω (g(n)) iff there exists positive constants c and n0 such that f(n) ≥
c * g(n) for all n, n ≥ n0.
Answer :
1.True 2. False 3.True

Short Questions ( 1 Marks)


1. Define the term data object.
Data object refers to set of elements (D) of specific data type which may be finite or
infinite.
2. What is time complexity of the following piece code?
while(n>0)
n = n/2
If n = 4, then the while loop will execute 2 times as log2(4)=2. If the array’s length is
8, then we the while loop will execute 3 times as as log2(8)= 3. So time complexity is
O(log2n).
3. State the difference between linear and nonlinear data structures.
Sr.No Linear Data Structures Non Linear Data Structures
1. Data is arranged in sequence. Data is not arranged in sequence
2. Every element is related to its Every element is related to many
previous and next element. elements.
3. Elements have one-to-one Elements have one-to-many
relationship relationship.
4. Memory utilization is inefficient Memory utilization is efficient

4. Define ADT.
The programmer may have to create & implement his/her own data type to suit the
program requirements, such a data type is called Abstract Data Type.
The programmer has to decide what to store, what operations to perform & what
should be the rules to be followed.
5. Define D.S.
A data structure is a set of
a) Domain D i.e. a designed domain d ∈ D.
b) a set of functions F and
c) a set of Axioms A.
6. Give two examples of each of linear and non linear Data structures.
Linear Data Structures:
Examples:
1. Array, 2. Stack, 3. Queue4. Linked List
Nonlinear Data Structures:
Examples:
1. Tree, 2. Graph.
7. “Choice of good data structures improves program efficiency” Comment.
Data structure is a platform to store data in organized and efficient manner. It
improves efficiency so it is choice of programmer to select appropriate data structure
and use it according to convince.
8. List some common operations that can be performed on D. S
1. Create, 2. Insert, 3. Delete, 4. Display, 5. Sort, 6. Search
9. List advantages of D.S.
1. Localization of change.
2. Encapsulation.
3. Flexibility.
4. Representation independence.
5. Modularity.
6. Extensibility.
10. Define linear and nonlinear D.S.
Linear Data Structure: The Data Structure in which elements are arranged in a line
and form a sequence or a list is called Linear Data Structure.
Nonlinear Data Structure: The Data Structure in which elements have one-to-many
relationship between them and do not form a specific sequence is called Nonlinear
Data Structure.
11. List components of space complexity.
1. Fixed Part, 2. Variable part
12. Define Ω notation.
The function f(n) = Ω(g(n)) iff there exists positive constants c and n0 such that
f(n) ≥ c * g(n) for all n, where n>=n0
13. Which notation is used to denote lower bound?
Ω notation is used to denote lower bounds.
14. Which notation is used to denote upper bound?
O notation is used to denote upper bounds.
15. Define time complexity.
Time Complexity is the the amount of time the program requires to execute.
16. Which notation is used to denote Lower & upper bound?
θ notation is used to denote both lower and upper bounds.
17. What is ADT? What are the advantages of ADT?
The programmer may have to create & implement his/her own data type to suit the
program requirements, such a data type is called Abstract Data Type.
The programmer has to decide what to store, what operations to perform &
what should be the rules to be followed.
18. Arrange the following time complexities in decreasing order.
O(n2) , O(log2n), O(n), O(n3), O(n2), O(nlog2n)

n O(n) O(log O(nlo O(n2) O(2n) O(n3)


n) gn)
1 1 1 1 1 2 1
2 2 1 2 4 4 8
4 4 2 4 16 16 64
8 8 3 24 64 256 512
So, in decreasing order of time complexities the functions are arrange as O(n3),
O(2n), O(n2), O(nlogn), O(n), O(logn) and in increasing order of time complexities
the functions are arrange as O(logn), O(n), O(nlogn), O(n2), O(2n), O(n3).
19. Define O notation.
The function f(n) = O(g(n)) iff there exists positive constants c and n0 such that f(n)
≤ c * g(n) for all n, where n>=n0
20. Define θ notation.
The function f(n) = θ(g(n)) iff there exists positive constants c1, c2 and n0 such that
C1 *g(n) ≤ f(n) ≤ c2 * g(n) for all n, where n>=n0
Long Questions :[Marks:5]
1. Write short note on space complexity.
Deals with storage requirements. It is an amount of a memory a program needs to
execute.
Components of Space Complexity:
1. Fixed Part: This part is independent of the characteristics of the inputs and
outputs. It includes the memory space for simple variables, component variables,
constants etc,
2. Variable part: It consists of the space needed by variables whose size depends on
the particular problem instance being solved, the space needed by reference variables
and the recursion stack space.
Components of Space Complexity:
S(P) = c + Sp,
Where
c is constant and is the fixed part.
Sp is the variable part which depends on the instance characteristics i.e. the program
instance being run .
Example:
float area(float r)
{
return 3.142 *r *r;
}
Answer:
Sp = 0
c = 1,
S(P) = 1+ 0 =1
Chapter-II
Array as a Data Structure
I. Multiple Choice Questions:
1. The Complexity of Bubble sort algorithm is ________.
a. O(n) b. O(log n) c. O(n2) d. O(n log n)
2. Internal sorting is defined as ___________.
a. algorithm that uses tape or disk during the sort.
b. algorithm that uses main memory during the sort.
c. algorithm that uses comparisons during the sort.
d. None of the above.
3. In which searching algorithm, target is added at the end of list?
a. Sequential Search b. Sentinel Search
c. Binary Search d. None of the above
4. Quick sort divide input list into three parts, according to _______ element .
a. Pivot b. High c. Low d. Mid
5. In which algorithm design strategy the problem is divided into smaller sub-problems and
then each sub-problem is solved independently.
a. Divide and Conquer b. Dynamic Programming
c. Greedy algorithm d. None of the above
Answers:
1. d-2. b 3-b 4-a 5-a
II. Fill in the Blanks:
1. The process of arranging data in some logical order is known as ______.
2. Internal sorting method uses only the _______ memory during sorting process.
3. _________ is the lower bound on comparison based sorting.
4. Algorithms that do not require any extra space and sorting is said to happen in-place, or
for example within the array itself. This is called ______________.
5. In Bubble sort, if we have total n elements, then we need to repeat Bubble sort process for
____ times.
6. In counting sort, array elements sorted without _________ an array element.
Answers:
1. Sorting 2. Primary 3. O( n log n) 4. in-place sorting
5. n-1 6. comparing
III. State True or False
1. Binary search uses divide and conquer approach.
2. Counting sort is comparison based sorting algorithm.
3. Insertion sort is internal sorting algorithm.
4. Merge sort is not external sorting algorithm.
5. In quick sort only first element is selected as pivot element.

Answers:
1-T 2-F 3-T 4-F 5-F
IV. Short Answers:
1.Define Algorithm? Write essential properties of an algorithm.
An algorithm is a finite set of instructions that, if followed, accomplishes a particular task.
Essential properties of an algorithm are:
Input 2. Output 3. Definiteness 4. Finiteness 5. Effectiveness
1. Which design strategy does quick sort follow?
Divide and Conquer.
2. Justify the following statement “Sorted data makes searching process efficient”.
In sorted data if we want to find out any value which is exact the value in list of data,
then it directly return that value. If the value we are searching is smaller than the
value at present we are accessing, then we need to stop there which reduces our
searches.
3. Why array is called as built in data structures.
 Array is called built in data structure because it also helps in organizing and
efficiently using a large number of data of a particular type.
4. Which would be best choice of pivot element in Bubble sort?
Best case: Ο(n2)
Worst case: Ο(n2)
5. What is best case and worst case for Linear search?
Best case: Ο(1)
Worst case: Ο(n)
6. Give Any One example of unstable sorting method?
Ans: Quick sort
7. What is best case and worst case for insertion sort?
Best case: Ο(n)
Worst case: Ο(n)
8. What do you mean by external sorting?
The Sorting is done on data which is stored in main memory is called internal sorting.
9. What do you mean by external sorting?
The Sorting is done on data stored in auxiliary storage device is called external
sorting.
10. What is best case and worst case for Quick sort?
Best case: Ο(log2n)
Worst case: Ο(n2)
11. What is best case and worst case for merge sort?
Best case: Ο(log2n)
Worst case: Ο(log2n)
12. What is best case and worst case for sequential search?
Best case: Ο(1)
Worst case: Ο(n)
13. What is best case and worst case for binary search?
Best case: Ο(log2n)
Worst case: Ο(log2n)
14. Give example of method which is not inplace sort.
Merge Sort

V. Long Questions:
1. Calculate address of element A[2][1] in a character array A[3][4] the row major
representation (assume base address = 100).
Address of a[i][j] = Base address + (i * c + j) * sizeof(element size)
Total No. of columns (c) = 4 which is given in A[3][4]
i=2, j=1 & sizeof(element size) = 1 as char data type
Address of a[2][1] = 100 + (2 * 4 + 1 ) * 1
= 100 + (9) * 1
= 100+9
= 109
2. Calculate address of element A[2][2] in a float array A[3][4] the column major
representation (assume base address = 100).
Address of a[i][j] = Base address + (j * r + i) * sizeof(element size)
Total No. of columns (r) = 4 which is given in A[3][4]
i=2, j=2 & sizeof(element size) = 4 as char data type
Address of a[2][2] = 100 + (2 * 4 + 2 ) * 1
= 100 + (10) * 1
= 100+10
= 110
3. Calculate address of element A[2][3] in a int array A[3][4] the column major
representation (assume base address = 500).
Address Calculation : int a[3][4];
Address of a[i][j] = Base address + (j * r + i) *
sizeof(element size)
Total No. of rows (r) = 3
Address of a[2][3] = 500 + (3 * 3 + 2 ) * 2
= 500 + (11) * 2
= 500 + 22 = 522
4. Write formula for calculating address of any element in row major and column major
representation of two-dimensional array.
Row Major Representation:
Address of a[i][j] = Base address + (i * c + j) * sizeof(element size)
Column Major Representation:
Address of a[i][j] = Base address + (j * r + i) * sizeof(element size)
5. Write formula for calculating address of any element in multi-dimensional array.
To find address of a[i1][i2][i3]…[in] if array a[s1][s2][s3]..[sn] is given, then
Address of a[i1][i2][i3]…[in]=
Base Address+[i1*s2*s3*.....sn+i2*s3*…sn+i3*s48…sn+in-1*sn+in]*element-size
6. Calculate address of element A[6][5] [4][3]in a int array A[7][6][5][4] (assume base
address = 500).
Address of a[i1][i2][i3]…[in]=
Base Address+[i1*s2*s3*.....sn+i2*s3*…sn+i3*s48…sn+in-1*sn+in]*element-size
So, Address of A[6][5][4][3]= Base Address + [i1*s2*s3*s4+i2*s3*s4+i3*s4+i4]*2
= 500 + [6*6*5*4+5*5*4+4*4+3]*2
= 500 + [720+100+16+3]*2
= 500 +[839]*2
= 500 + 1678
= 2178
7. Write function for merge sort, bubble sort and binary search.
Merge Sort:
void mergesort(int a[], int low, int high)
{
int mid;
if(low<high)
{
mid = (low+high)/2;
mergesort(a, low,mid);
mergesort(a, mid+1,high);
merge(a,low,mid,high);
}
}
void merge(int a[], int low, int mid,int high)
{
int I, j, k, b[10];
i=low;
j=mid+1;
k=0;
while((i<=mid)&&(j<=high))
{
if(a[i]<a[j])
{
b[k]=a[i];
i++;
k++;
}
while(j<=high)
{
b[k]=a[j];
k++;
j++;
}
for(i=low,k=0;i<=high;i++,k++)
a[i]=b[k];
}
Bubble Sort:
void bubble(int x[], int n)
{
int i,temp,pass;
cc=0;
sc = 0;
for(pass = 1; pass<n; pass++)
{
for(i=0; i<n-pass;i++)
{
cc++;
If(x[i]≥x[i+1])
{
sc++;
temp = x[i];
x[i]=x[i+1];
x[i+1] = temp;
}
}
}
}
Binary Search:
int recbinsearch(int a[ ], int top, int bottom, int key)
{
int mid;
if(top<=bottom)
{
mid = (top +bottom)/2;
If(a[mid]==key)
return mid;
else if(key < a[mid])
return recbinsearch(a, top, mid-1, key);
else
return recbinsearch(a, mid+1, bottom, key);
}
return -1;
}
Bubble Sort:
void bubble(int x[], int n)
{
int i,temp,pass;
cc=0;
sc = 0;
for(pass = 1; pass<n; pass++)
{
for(i=0; i<n-pass;i++)
{
cc++;
If(x[i]≥x[i+1])
{
sc++;
temp = x[i];
x[i]=x[i+1];
x[i+1] = temp;
}
}
}
}
8. Sort the following data in ascending order using bubble sort.
Neena, Ajay, Piyush, Bharti, Leena, Atul
Pass 0:
Ajay, Neena, Piyush, Bharti, Leena, Atul
Ajay, Neena, Piyush, Bharti, Leena, Atul
Ajay, Neena, Bharti, Piyush, Leena, Atul
Ajay, Neena, Bharti, Leena,Piyush, Atul
Ajay, Neena, Bharti, Leena, Atul, Piyush
Pass 1:
Ajay, Neena, Bharti, Leena, Atul, Piyush
Ajay, Neena, Bharti, Leena, Atul, Piyush
Ajay, Bharti, Neena,Leena, Atul, Piyush
Ajay, Bharti, Leena, Neena, Atul, Piyush
Ajay, Bharti, Leena, Atul, Neena, Piyush
Pass 3:
Ajay, Bharti, Leena, Atul, Neena, Piyush
Ajay, Bharti, Leena, Atul, Neena, Piyush
Ajay, Bharti, Atul, Leena, Neena, Piyush
Pass 4:
Ajay, Bharti, Atul, Leena, Neena, Piyush
Ajay, Atul, Bharti, Leena, Neena, Piyush
9. Sort the following data in ascending order using insertion sort.
10. 48, 17, 25, 89, 55, 8
Sorted List Unsorted List
Empty 48, 17, 25, 89, 55, 8
48 17, 25, 89, 55, 8
17, 48 25, 89, 55,8
17,25, 48 89, 55, 8
17, 25, 48, 89 55, 8
17, 25, 48, 55,89 8
8, 17, 25, 48, 55, 89 Empty
11. Sort the following data in ascending order using insertion sort.
27, 9, 7, 39, 35, 2
Sorted List Unsorted List
Empty 27, 9, 7, 39, 35, 2
27, 9,7, 39, 35, 2
9, 27 7, 39, 35, 2
7, 9, 27 39, 35,2
7, 9, 27, 39 35, 2
7, 9, 27, 35 , 39 2
2, 7, 9, 27, 35, 39 Empty
12. Sort the following data in ascending order using merge sort.
14, 2, 99, 34, 23, 67, 100, 107
[14, 2, 99, 34] [23, 67, 100, 107]
[14, 2] [99, 34] [23, 67] [100, 107]
[14] [2] [99] [34] [23] [67] [100] [107]
[2, 14] [34, 99] [23, 67] [100, 107]
[2, 14, 34, 99] [ 23, 67, 100, 107]
[2, 14, 23, 34, 67, 99, 100, 107]
2, 14, 23, 34, 67, 99, 100, 107
25, 45,55, 20, 35, 40, 12, 10
13. Sort the following data in ascending order using quick sort.
89, 14, 10, 25, 99, 75, 12, 77, 97
[14, 10, 25, 75, 12, 77] 89 [ 99,97]
[10, 12] 14 [25, 75, 77] 89 [97] 99
10 [12] 14, 25 [75, 77] 89 97 99
10, 12, 14, 25, 75 [77] 89, 97, 99
10, 12, 14, 25, 75, 77, 89, 97, 99
10, 12, 14, 25, 75, 77, 89, 97, 99
14. Sort the following data in ascending order using merge sort and quick sort.
25, 45,55, 20, 35, 40, 12, 10 and 20, 54, 48, 37, 12, 92, 86, 07
15. Write a note on sequential Search.
int linsearch(int a[], int n, int key)
{
int i,k;
for(i=0;i<n;i++)
{
if(a[i]==key)
return i;
else
k= -1;
}
return k;
}
16. Write recursive and non recursive function for Binary Search.
Non Recursive :
int binsearch(int a[], int n, int key)
{
int mid, top, bottom;
top =0;
bottom = n-1;
while(top<bottom)
{
mid = (top+bottom)/2;
if(a[mid]==key)
return mid;
else
if(key <a[mid])
bottom =mid – 1;
else
top = mid +1;
}
return -1;
}
int recbinsearch(int a[ ], int top, int bottom, int key)
{
int mid;
if(top<=bottom)
{
mid = (top +bottom)/2;
If(a[mid]==key)
return mid;
else if(key < a[mid])
return recbinsearch(a, top, mid-1, key);
else
return recbinsearch(a, mid+1, bottom, key);
}
return -1;
}
17. Write function for Quick Sort.
void quicksort(int a[], int lb, int ub)
{

int j;
if(lb<ub)
{
j=partition(a,lb,ub);
quicksort(a,lb,j-1);
quicksort(a, j+1, ub);
}
}
int partition(int a[], int lb, int ub)
{
int i,j,pivot,temp;
i=lb+1;
j=ub;
pivot=a[lb];
do
{
while((a[i]<pivot)&&(i<=ub))
i++;
while((a[j]>pivot)&&j>lb))
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);
a[lb]=a[j];
a[j]=pivot;
return j;
}
Chapter 3
LINKED LIST
I. Multiple Choice Questions:
1. A doubly linked list has .......... pointers with each node.
a. 0 b.1 c.2 d.3
2. In a linked list, insertion can be done as.........
a. Beginning b. end c. middle d. all of the above
3. The pointer that points to the first node in the list is........
a. HEAD b. AVAIL c. TOP d. REAR
4. What is the time complexity to count the number of elements in the linked list?
a. O(1) b. O(n) c. O(logn) d. None of the mentioned
5. Linked list is considered as an example of ___________ type of memory allocation.
a. Dynamic b. Static c. Compile time d. None of the mentioned

ANSWERS
1.b 2.d 3.a 4.b 5.a
II. Fill in the Blanks
1. The data structures you will use if you want to go to first record from the last and vice
versa______________
2. _________linked list is also called as two way linked list.
3. _________function is used to dynamically allocate memory in C.
4. __________linked list is used to represent polynomial equation with multiple variables.

5. _________function is used to release the memory which is dynamically allocated in C.


6. ________ pointer indicate end of linked list.
ANSWERS:
1.Doubly Circular Linked List 2. Doubly Circular Linked List 3. malloc () 4.
Generalized Linked List 5.free () 6.NULL
III. State True or False
1.Linked list is examples of static data structures.
2. A linked list is a linear collection of self-referential structures, called nodes, connected by
pointer links—hence, the term "linked" list.
3. Linked list nodes are normally stored contiguously in memory.
4.The next item in a linked list always can be found by accessing the next physical location
in memory.
5. Node of doubly linked list has 2 pointers.
6.Linked list is non-linear data structure.
7.The length of a linked list is the number of nodes in the list.
ANSWERS:
1.False 2.True 3. False 4. False 5. True 6. False 7. True

IV. Short Answers:


1. Define node structure of S.L.L
struct node
{
int info;
struct node *next;
};
2. Define node structure of S.C.L.L
struct node
{
int info;
struct node *next;
};
3. Define node structure of D.L.L
struct node
{
int info;
struct node *next,*prev;
};
4. Define node structure of D.C.L.L
struct node
{
int info;
struct node *next,*prev;
};
5. Define node structure of Generalized linked list.
Struct node
{
int tag;
union
{
int info;
struct node *next
}info;
struct node *next;
};
6. “A linked list can traversed sequentially”. State TRUE or FALSE.
A linked list is linear data structure and form a sequence so a linked list can traversed
sequentially.
7. “Linked List is linear data structure”. Comment it.
The Data Structure in which elements are arranged in a line and form a sequence or a
list is called Linear Data Structure so Linked list is linear data structure.
8. What are advantages of D.L.L.
Doubly linked list can be traversed in both forward and backward directions.
To delete a node in singly linked list, the previous node is required, while in doubly
linked list, we can get the previous node using previous pointer.
It is very convenient than singly linked list. Doubly linked list maintains the links for
bidirectional traversing.
9. What are applications of Linked list.
The linked list is a dynamic data structure.
You can also decrease and increase the linked list at run-time. That is, you can
allocate and deallocate memory at run-time itself.
In this, you can easily do insertion and deletion functions. That is, you can easily
insert and delete the node.
Memory is well utilized in the linked list. Because in it, we do not have to allocate
memory in advance.
Its access time is very fast, and it can be accessed at a certain time without memory
overhead.
You can easily implement linear data structures using the linked list like a stack
10. List primitive operations applied on linked list.
1) Create 2) Traverse 3)Insert 4)Delete 5) Display
6) Search 7) Concatenation 8)Sorting 9)Reverse 10) Merge
V. Long Questions:
1. What is generalized linked list.
A generalized list L is a finite sequence of n elements (n ≥ 0). The element is either an
atom (single element) or another generalized list. The elements that are not atoms,
they will be sub-list of L.
Node
Where, Flag=0 means data and next pointer exists.
Flag=1 means down pointer exists (Starting of sub list)
Data is the value which is store in the list.
Down pointer contains the address of node which is down of current node.
Next pointer contains the address of next node in the list.
C Structure to represent a node of generalized link list
2. Write a function to insert a node in singly linked list.
struct node *insert(struct node *head)
{
struct node *p=NULL, *temp=NULL;
int x,pos,i;
printf(“Enter position”);
scanf(“%d”,&pos);
for(temp=head,i=1; i<=pos-1&&temp!=NULL;i++)
{
temp=temp->next;
}
If(temp!=NULL)
{
print(“Enter Actual Value to insert”);
p=(struct node *)malloc(sizeof(struct node));
scanf(“%d”, &x);
p>info=x;
p->next=NULL;
p->next=temp->next;
temp->next=p;
}
else
{
printf(“\n Position out of order”);
}
return(head);
}
3. Write a function to insert a node in doubly linked list.
struct node *insert(struct node *head)
{
int pos, i,x;
strcut node *temp=NULL, *p=NULL,*temp1=NULL;
printf(“ Enter the position”);
scanf(“%d”,&pos);
for(temp=head,i=1;i<=pos-1&&temp!=NULL;i++)
{
temp=temp->next;
}
If(temp!=NULL)
{
printf(“Enter actual value to insert”);
p=(struct node *)malloc(sizeof(struct node));
scanf(“%d”, &x);
p->info=x;
p->next=p->prev=NULL;
if(temp->next!=NULL)
{
temp1=temp->next;
p->next=temp1;
temp1->prev=p;
temp->next=p;
p->prev=temp;
}
else
{
temp->next=p;
P->prev=temp;
}
}
else
{
printf(“\n Position out of order\n”);
}
return(head);
}
4. Write a function to insert a node in singly circular linked list.
struct node *insert(struct node *head)
{
struct node *p=NULL, *temp=NULL;
Int pos,I;
Printf(“\n Enter position”);
scanf(“%d”,&pos);
for(temp=head,i=1; i<=pos-1&&temp->next!=NULL;i++)
{
temp=temp->next;
}
if((i<=pos-1)&&(temp->next!=head))
{
printf(“\nPosition Out Of Order\n”);
}
else
{
print(“Enter Actual Value to insert”);
p=(struct node *)malloc(sizeof(struct node));
scanf(“%d”, &x);
p>info=x;
p->next=NULL;
p->next=temp->next;
temp->next=p;
}
return(head);
}
5. Write a function to delete a node from singly linked list.
struct node *delete(struct node *head)
{
struct node *p=NULL, *temp=NULL;
int pos,i;
printf(“Enter position”);
scanf(“%d”,&pos);
for(temp=head,i=1; i<=pos-1&&temp->next!=NULL ;i++)
{
temp=temp->next;
}
if(temp->next!=NULL)
{
p= temp->next;
printf(“\n The deleted element is %d”, p->info);
temp->next=p->next;
free(p);
}
else
{
printf(“\n Position out of order”);
}
return(head);
}
6. Write a function to delete a node from Doubly Circular Linked List.
struct node *delete(struct node *head)
{
struct node *p=NULL, *temp=NULL;
int pos,i;
printf(“\n Enter position”);
scanf(“%d”,&pos);
for(temp=head,i=1;i<=pos-1&&temp->next!=NULL;i++)
{
temp=temp->next;
}
if((i<=pos-1)&&(temp->next!=head))
{
printf(“\nPosition Out Of Order\n”);
}
else
{
p=temp->next;
printf(“\nThe deleted element is %d”,p->info);
temp->next=p->next;
free(p);
}
return(head);
}
7. Write a function to delete a node from doubly Circular linked list.
struct node *delete(struct node *head)
{
int pos, i,x;
strcut node *temp=NULL, *p=NULL,*temp1=NULL;
printf(“ Enter the position”);
scanf(“%d”,&pos);
for(temp=head,i=1;i<=pos-1&&temp->next!=head; i++)
{
temp=temp->next;
}
If(temp->next!=head)
{
p=temp->next;
printf(“\n The deleted info is %d”, p->info);
If(p->next!=head)
{
temp1= p->next;
temp1=temp->next;
temp=temp1->prev;
}
else
{
temp->next = NULL;
free(p);
}}
else
{
printf(“\n Position out of order\n”);
}
return(head);
}
8. Write a function to merge two sorted linked list.
struct node *merge(struct node *head1, struct node *head2, struct node *head3)
{
struct node *t1=NULL, *t2=NULL, *t3=NULL, *p=NULL;
t1= head1->next;
t2=head2->next;
t3=head3->next
while(t1!=NULL&&t2!=NULL)
{
p= (struct node*)malloc(sizeof(struct node));
p->next=NULL;
if(t1->info < t2->info)
{
p->info=t1->info;
t1=t1->next;
}
else
{
p->info=t2->info;
t2=t2->next;
}
t3->next=p;
t3=t3->next;
}
if( t1!=NULL)
t3->next=t1;
If(t2!=NULL)
t3->next=t2;
return(head3);
}
9. Write a function to add two polynomial.
struct node *add(struct node *p1, struct node *p2, struct node *p3)
{
struct node *t1=p1->next, *t2=p2->next, *t3=p3, *p=NULL;
while(t1!=NULL&&t2!=NULL)
{
p= (struct node*)malloc(sizeof(struct node));
p->next=NULL;
if(t1->exp >t2->exp)
{
p->exp=t1->exp;
p->coef=t1->coef;
t1=t1->next;
}
if(t1->exp < t2->exp)
{
p->exp=t2->exp;
p->coef=t2->coef;
t2=t2->next;
}
else
{
p->exp=t1->exp;
p->coef=t1->coef+t2->coef;
t1=t1->next;
t2=t2->next;
}
t3->next=p;
t3=p;
}
if(t1!=NULL)
t3->next=t1;
if(t2!=NULL)
t3->next=t2;
return(t3);
}
10. Write a function to concateneate a singly linked list of integers.
void concatenate(struct node *head1, struct node *head2)
{
struct node *temp1=NULL, *temp2=NULL, *p=NULL;
for(temp1=head1;temp1->next!=NULL;temp1=temp1->next);
for(temp2=head2->next;temp2!=NULL;temp2=temp2->next)
{
p=(strcut node*)mallloc(sizeof(struct node));
p->info=temp2->info;
p->next=NULL;
temp1->next=p;
temp1=p;
}
}
Chapter-4
Stack

I. Multiple choice questions:


1. To implement pop function, which operation sequence is used?
a) top is incremented by 1 and assign a value to variable.
b) top is decremented by 1 and assign a value to variable.
c) Assign a value to variable and top is decremented by 1.
d) Assign a value to variable and top is incremented by 1.
2. The following sequence of operation is performed on a stack push(4), pop, push(4), pop,
push(4), push(4), push(5), pop, pop, pop. After pop operation output of stack ----
a) 4, 4, 5, 4, 4 b) 4, 4, 4, 4, 5
c) 5, 4, 4, 4, 4 d) 4, 5, 4, 4, 4
3. The result of evaluation of postfix expression is uvw*-, where u=4, v=3 and w=10.
a) 26 b) -26 c) 2 d) -2
4. To implement push function, which operation sequence is used?
a) top is incremented by 1 and assign a value to variable.
b) top is decremented by 1 and assign a value to variable.
c) Assign a value to variable and top is decremented by 1.
d) Assign a value to variable and top is incremented by 1.
5. The result of evaluation of postfix expression is +u*wv where u=4, v=3 and w=10.
a)26 b) -26 c)2 d)-2
6. The following sequence of operation is performed on a stack push(A), push(B), pop, pop,
push(A), push(A), push(B), pop, pop, pop. After pop operation output of stack --
a) B, B A, A, A b) B, A, B, A, A
c) A, A, B, B, B d) A, A, A, B, B
ANSWERS:
1-c, 2-a, 3-b, 4a, 5-b, 6-b,

II. Fill In The Blank:


1. Insertion operation in stack is called------------------.
2. Deletion operation in stack is called -----------------.
3. Insertion and deletion operation is possible only at -----------end.
4. Stack has both ------------ and -------------- implementation.
5. When multiple operators are used in an expression, they are evaluated according to
their---------.
6. In static implementation of stack, ---------- data structure is used.
6. In dynamic implementation of stack, ---------- data structure is used.
8. ---------------strategy is performed according to implicit and explicit constraints.
ANSWERS:
1. Push 2.pop 3.top 4.Static and Dynamic
5.Precedence 6. Array7. Linked list 8. Backtracking
III. True or False
1. Stack is nonlinear data structure.
2. To display top element in stack, push operation is used.
3. Different data type elements are allowed.
4. Stack uses LIFO basis, so access is of top element only.
5. For all expression conversion methods, static stack implementation is applied.
Answers:
1.False 2.False 3.True 4. True 5.True

IV. Short questions:


1. Define stack.
Stack is an order collection of items which was arranged in last in first out
manner.
Insertion and deletion of element is possible from one end onlyis called top
end.
2. Define infix, postfix and prefix.
Infix : The operator is in between two operand.
Example A+B, (A+B)*C
Prefix : The operator precedes the two operands.
Example +AB, *+ABC
Postfix : The operator follows the two operands.
Example AB+, AB+C*
3. Give applications of stack.
1. Expression conversion & evaluation.
2. Checking whether parentheses are matching in an expression.
3. Handling function calls, Recursion.
4. Interrupt handling in processors.
5. Non recursive traversal of tree &graph.
6. Backtracking Algorithms.
7. Games.
4. What is LIFO.
Stack uses basis as Lat In First Out.
5. List operations of stack.
1. Create
2. push
3. pop
4. isempty
5. isfull
6. peek
6. Name D.S used for recursion.
Stack.
7. Define Multiple Stack.
Multiple Stack: When more than one stack is used, then such a concept is called
multiple stack.
Suppose we want to implement ‘k’ stacks in a single array the following steps are
used:
1. Divide array into ‘k’ equal parts.
2. Each part can be a stack.
3. If array size is n, then each part will be of n/k locations.
4. The top of first stack will be initialized to -1.
5. The top of mth stack will be initialized to (m-1)n/k-1.
6) What are the applications of stack?
1)In a single processor multitasking computer, job(s) wait to be processed form a queue.

2) Same happens when we share a printer with many computers. Compiling an HLL code.

3)Using the download manager, for multiple files also uses a queue for ordering the files.

4) In multiuser OS – job scheduling is done through a queue.

Long Questions:
1. Write a function push and pop using array.
Push:
void push(struct stack *ps, int x)
{
++ps->top;
ps->data[ps->top]=x;
}
Pop:
int pop(struct stack *ps)
{
int x;
x=ps->data[ps->top];
ps->top--;
return x;
}
2. Write a function push and pop using S.L.L.
void dspush() //dynamic stack push
{
nw=(struct node*)malloc(sizeof(struct node));
printf(“\n Enter the value to be pushed\n”);
scanf(“%d”,&nw->data);
nw->next=NULL;
if(top==NULL)
{
top=nw;
}
else
{
nw->next=top;
top=nw;
}
void dspop() //dynamic stack pop
{
int x;
temp=top;
x=temp->data;
printf(“\n The popped element is %d”,x);
top=top->next;
free(temp);
}
3. Write a function to check whether a expression is fully parenthesized?
void wellparen(char infix[])
{
char c;
int k, t=1;
struct stack sp;
ssinit(&sp);
for(k=0;infix[k]!= ‘\0’;k++)
{
If(infix[k]== ‘(’||infix[k]== ‘{’||infix[k]== ‘[’)
{
sspush(&sp,infix[k]);
}
else if(infix[k]== ‘)’)
{
c=sspop(&sp);
if(c!= ‘(’)
t=0;
}
else if(infix[k]== ‘}’)
{
c=sspop(&sp);
if(c!= ‘{’)
t=0;
}
else if(infix[k]== ‘]’)
{
c=sspop(&sp);
if(c!= ‘[’)
t=0;
}
else
continue;
if((!ssisempty(&s))&&(t!=0))
printf(“\n The expression is not well-parenthesized expression”);
else
printf(“\n The expression is well-parenthesized expression”);
}
4. Give the output of the following sample code:

initstack(s);
push(s, 9);
push(s, 4);
i=pop(s);
while(i > 0)
{
Push(s, i*i);
while(i > 0)
{
Push(s, i*i);
i--;
}
while(!stackempty(s))
prinf(“%d\n”,pop(s));
Output: 1, 4, 9, 16, 9
1. Write a function to evaluate postfix expression.
void postfixeval(char postfix[])
{
struct stack sp;
ssinit(&sp);
int k,val,od1,od2,result;
for(k=0;postfix[k]!= ‘\0’;k++)
{
if(isalpha(postfix[k]))
{
printf(“\n Enter value of %c”, postfix[k]);
scanf(“%d”,&val);
sspush(&sp,val);
}
else
{
od2=sspop(&sp);
od1=sspop(&sp);
if(postfix[k]== ‘+’)
{
val=od1+od2;
sspush(&sp,val);
}
else if(postfix[k]== ‘-’)
{
val=od1-od2;
sspush(&sp,val);
}
else if(postfix[k]== ‘*’)
{
val=od1*od2;
sspush(&sp,val);
}
else if(postfix[k]== ‘/’)
{
val==od1/od2;
sspush(&sp,val);
}
else
{
val=od1^od2;
sspush(&sp,val);
}
}
result=sspop(&sp);
printf(“\nThe result is %d”,result);
}
2. Write a function to reverse stack.
void reverse()
{
struct stack s;
initstack(&s);
char a[30],ch;
int i;
printf(“Enter the string”);
gets(a);
printf(“\n The given string is \n”);
puts(a);
printf(“\The reverse string is\n”);
for(i=0;a[i]!=‘\0’;i++)
{
if(a[i]==‘ ‘)

{
while(!isempty(&s))
{
ch=pop(&s));
printf(“%c”,ch);
}
}
else
{
push(&s,a[i]);
}
printf(“ “);
}
while(!isempty(&s))
{
ch=pop(&s);
printf(“%c”,ch);
}
}

ii)Second Method
3. /* C Program To Reverse String using Stack */

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 20
int top = -1;
char stack[MAX];
char pop();
void push(char);
int main()
{
char str[20];
unsigned int i;
printf("Enter the string : " );
gets(str); /*Push characters of the string str on the stack */
for(i=0;i<strlen(str);i++)
push(str[i]); /*Pop characters from the stack and store in string str */
for(i=0;i<strlen(str);i++)
str[i]=pop(); printf("\nReversed string is : ");
puts(str);
return 0;
}/*End of main()*/
void push(char item)
{ if(top == (MAX-1))
{ printf("\nStack Overflow\n");
return;
}
stack[++top] =item;
}/*End of push()*/
char pop() { if(top == -1)
{
printf("\nStack Underflow\n"); exit(1);
} return stack[top--];
}/*End of pop()*/

4)Write a function to convert infix expression to postfix expression.


void postfix(char in[], char post[])
{
int i,j=0;
char ch1;
Struct stack s;
initstack(&s);
for(i=0;in[i]!=‘\0’;i++)
{
if(in[i]==‘+’||in[i]==‘-’||in[i]==‘*’||in[i]==‘/’||in[i]==‘^’)
push(&s,in[i])
else if(in[i]==‘)’)
{
while((ch1=pop(&s))!=‘(‘)&&(!isempty(&s)))
post[j++]=ch1;
else
post[j++]=in[i];
}
while(!isempty(&s))
{
post[j]=pop(&s);
J++;
}
post[j]=‘\0’;
}
4. Write a function to convert infix expression to prefix expression.
char sttop(struct stack *sp)//To return topmost element
{
return(sp->items[st->top]);
}
int prior(char c)// To find out priority
{
int m;
if(c== ‘(’)
m=0;
else if(c== ‘+’||c== ‘-’)
m=1;
else if(c== ‘*’||c== ‘/’)
m=2;
else if(c== ‘^’)
m=3;
else
m=0;
return m;
}
char prefixcon(char infix[], char rev[])
{
int k,m,c,j=0;
struct stack sp;
ssinit(&sp)
strrev(infix);
for(k=0;infix[k]!= ‘\0’;k++)
{
if(infix[k]== ‘(’)
sspush(&sp, infix[k]);
else
if(infix[k]== ‘)’)
{
while(((!ssisempty(&sp))&&(c=sspop(&sp))!= ‘(’)
{
rev[j]=c;
j++;
}
}
else if(infix[k]== ‘+’||infix[k]== ‘-’||infix[k]== ‘*’||infix[k]== ‘/’||infix[k]== ‘^’)
{
if(ssisempty(&sp))
sspush(&sp,infix[k]);
else
{
while((!ssisempty(&sp))&&(prior(infix[k])<=prior(sttop(&sp))))
{
rev[j]=sspop(&sp);
j++;
}
}
}
else if(infix[k]== ‘)’)
{
while((!ssisempty(&sp))&&((c=sspop(&sp))!= ‘(’)
{
rev[j]=c;
j++;
}
}
else
{
rev[j]=infix[k];
j++;
}
}
while(!ssisempty(&sp))
{
rev[j]=sspop(&sp)
j++;
}
rev[j]= ‘\0’;
}
strrev(rev);
}
Chapter-5
Queue

I. Multiple Choice Questions


1 . The following sequence of operation is performed on a linear queue insert(4), remove,
insert(4), remove, insert(4), insert(4), insert(5), remove, remove, remove. After remove
operation output of linear queue ----
a) 4, 4, 5, 4, 4 b) 4, 4, 4, 4, 5
c) 5, 4, 4, 4, 4 d) 4, 5, 4, 4, 4
2. In which queue while removing an element, the data element with highest priority is
removed first?
a) Deque b) Circular queue c) Linear queue d) Priority queue
3. In CPU scheduling, the data structures used is ----------.
a) Queue b) Stack c) Linked list d) Array
4. To implement remove function from linear queue, which operation sequence is used?
a) front is incremented by 1 and assign a value to variable.
b) front is decremented by 1 and assign a value to variable.
c) Assign a value to variable and front is decremented by 1.
d) Assign a value to variable and front is incremented by 1.
ANSWERS:
1-b , 2-d , 3-a , 4-d
II. Fill in the Blanks
1. ------------ queue is used to implement RR(Round Robin) algorithm.
2. In Circular queue, rear is incremented with --------------.
3. Queue has both ------------ and -------------- implementation.
4. In static implementation of Circular queue, ---------- data structure is used.
5. In dynamic implementation of Circular queue, ---------- data structure is used.
6. ---------- is the operation to remove element from a queue.
ANSWERS:
1.Circular Deque 2.rear=(rear+1)% SIZE 3. static and dynamic
4. Array 5. Linked list 6. Dequeue

III. State True or False


1. Queue is nonlinear data structure.
2. Queue uses FILO basis, so element which is inserted first is deleted last.
3. In Circular queue is also known as Ring Buffer.
ANSWERS:
1. False 2. False 3. True

IV. Short Questions:


1. Define Queue.
It is ordered collection of items from which items may be deleted or removed
from one end called front and into which items may be inserted at other end is
called rear.
It uses basic as FIFO ( First In First Out) manner.
2. Define Circular Queue.
The elements are arranged in a sequential manner but can logically be regarded as
arranged circularly.
3. Define Priority Queue.
Elements are arranged according to their priority. The queue operations are performed
according to priority of elements.
4. List primitive operations on queue.
i. Create.
ii. Add.
iii. isfull
iv. Delete.
v. Isempty.
vi. Peek.
5. Write a statement to increment rear and front in circular queue implemented using
array.
pq->rear= (pq->rear+1) %MAX;
pq->front = (pq->front +1) %MAX;
6. Define double priority queue.
The operations add and remove can be performed from both the ends.
Thus this queue supports 4 basic operations.
7. Give two applications of Queue.
i. In scheduling of resources like CPU, printer etc
ii. Multiple print jobs given to printer.
iii. In batch programming, multiple jobs are combined into a batch &
programs are executed in FIFO order.
iv. In BFS of graph & levelwise traversal of tree.

V. Long Questions :
1. Write a function to ADD and DELETE functions to implement dynamic
representation of linear queue.
void insert(int item)
{
Node *newnode;
newnode=(Node*)malloc(sizeof(Node));
newnode ->data=item;
newnode ->next=NULL;
if(front==NULL)
front=rear= newnode;
else
{
rear->next= newnode;
rear= newnode;
}}
int del()
{
int item;
Node *temp=front;
item=front->data;
front=front->next;
free(temp);
if(front==NULL)
rear=NULL;
return(item);
}
2. Write a function to ADD and DELETE functions to implement static representation
of linear queue.
int isfull(Queue *q)
{
if(q->rear==MAX-1)
return(1);
else
return(0);
}
void enqueue(Queue *q,int item)
{
q->rear++;
q->que[q->rear]=item;
}
int isempty(Queue *q)
{
if(q->front==q->rear)
return(1);
else
retrun(0);
}
int dequeue(Queue *q)
{
int item;
q->front++;
item=q->que[q->front];
return(item);
}

3. Write a function to ADD and DELETE functions to implement static representation


of circular queue.
int isfull(cqueue *q)
{
if((q->front==q->rear+1)||(q->front==0&&q->rear==max-1))
return(1);
else
return(0);
}
int isempty(cqueue *q)
{
if(q->front==-1)
return(1);
else
return(0);
}
void insert(cqueue *q,int item)
{
if(q->front==-1)
q->front=0;
q->rear=(q->rear+1)%max;
q->que[q->rear]=item;
printf("\nInserted");
}
int del(cqueue *q)
{
int item;
item=q->que[q->front];
if(q->front==q->rear)
{
q->rear=-1;
q->front=-1;
}
else
q->front=(q->front+1)%max;
return(item);
}}
4. Write a function to ADD and DELETE functions to implement static representation
of circular queue.
void enqueue(int item) // function to insert the element in the Queue
{
Node *newnode; // declaration of pointer of struct node type.
newnode=(Node *)malloc(sizeof(Node)); // allocating the memory to the newnode
newnode->data=item;
newnode->next=NULL;
if(rear==NULL) // checking whether the Queue is empty or not.
{
front=rear=newnode;
rear->next=front;
}
else
{

rear->next=newnode;
rear=newnode;
rear->next=front;
}
}

int dequeue() // function to delete the element from the queue


{
Node *temp; // declaration of pointer of node type
temp=front;
int item=temp->data;
if((front==NULL)&&(rear==NULL))
printf("\nQueue is empty");
else if(front==rear) // checking whether the single element is left in the queue
{
front=rear=NULL;
free(temp);
}
else
{
front=front->next;
rear->next=front;
free(temp);
}
return(item);
}
5. Write a note on Deque.
It is ADT(Abstract Data Type) having Property of queue with additionally each
element has a priority associated to it.
I. To understand priority queue in detail we take the basic example of queue.
II. Suppose there are some patients waiting in a queue for their number at the
outside of the doctors room. Suppose there are 9 patients waiting in a queue
and meanwhile 3 patients come who are having emergency, the doctor can
leave the patients who wait in a queue and turn to emergency patients as per
priority.

In this type of queue elements are processed by following two points.


1. Element having highest priority process first than element having lowest priority.
2. If two elements are of the same priority then they are processed by their order.
Two types of Priority Queue are as follows.
1. Ascending Priority Queue: Elements can be inserted in any order (arbitrarily) but
only the smallest element can be removed. For example, suppose there is an array
having elements 6,1,9 in the same order. So, while inserting the elements, the
insertion will be in the same sequence but while deleting, the order will be 1,6,9.
2. Descending priority Queue: Element can be inserted in any order but only the
largest element can be removed first from the given Queue. For example, suppose
there is an array having elements 6,1,9 in the same order. So, while inserting the
elements, the insertion will be in the same sequence but while deleting, the order will
be 9,6,1.
Implementation of Priority Queue

We can implement priority queue by using following methods


Method 1
1. Add the rear.
2. Remove by selecting the largest element.
Method 2
1. Insert element in sorted manner.
2. Remove from the front.
Method 2 is more efficient to maintain the queue as a sorted set of elements is
available rather than search for the largest element while deleting the element from
the queue. All operations are same as linear queue except the insert operation.

This work is licensed under a Creative Commons Attribution-


NonCommercial-ShareAlike 4.0 International License.

"Question Bank" by Mrs. Galande C.S is licensed under CC BY-NC-SA 4.0

You might also like