Notes Part1
Notes Part1
Linear: A data structure is said to be linear if its elements form a sequence or a linear list.
Examples: Array. Linked List, Stacks and Queues
Non-Linear: A data structure is said to be non-linear if the traversal of nodes is nonlinear in
nature. Example: Graph and Trees.
What is an Algorithm?
An algorithm is a process or a set of rules required to perform calculations or some other problem- solving
operations especially by a computer. The formal definition of an algorithm is that it contains the finite set of
instructions which are being carried in a specific order to perform the specific task. It is not the complete
program or code; it is just a solution (logic) of a problem
GAURAV BHATIA
1
Characteristics of an Algorithm
o Input: An algorithm has some input values. We can pass 0 or some input value to an
algorithm.
o Output: We will get 1 or more output at the end of an algorithm.
o Unambiguity: An algorithm should be unambiguous which means that the instructions in an
algorithm should be clear and simple.
o Finiteness: An algorithm should have finiteness. Here, finiteness means that the algorithm
should contain a limited number of instructions, i.e., the instructions should be countable.
o Effectiveness: An algorithm should be effective as each instruction in an algorithm affects
the overall process.
o Language independent: An algorithm must be language-independent so that the instructions
in an algorithm can be implemented in any of the languages with the same output.
GAURAV BHATIA
2
Simple program to understand how pointer works
#include <stdio.h>
int main( )
{
int a = 5;
int *b;
b = &a;
printf ("value of a = %d\n", a); printf
("value of a = %d\n", *(&a));printf
("value of a = %d\n", *b); printf
("address of a = %d\n", b); printf
("address of b = %u\n", &b);
printf ("value of b = address of a = %u", b);return 0;
}
Output
value of a = 5
value of a = 5
address of a = 3010494292
address of b = 3010494296
value of b = address of a = 3010494292
It's purpose is to print a pointer value in an implementation defined format. The corresponding argument
must be a void * value.
And %p is used to printing the address of a pointer the addresses are depending by our system bit.
#include <stdio.h>
GAURAV BHATIA
3
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
Example:
int arr[5] = { 1, 2, 3, 4, 5 };
Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes.
#include <stdio.h>
int main()
{
int arri[] = {1, 2 ,3};
int *ptri = arri;
return 0;
}
OutPut:
sizeof arri[] = 12 sizeof ptri = 4 sizeof arrc[] = 3 sizeof ptrc = 4
Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually
increments by the number equal to the size of the data type for which it is a pointer.
GAURAV BHATIA
4
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and
the new address it will points to 1002. While if a float type pointer is incremented then it will increment by
4(size of a float) and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually
decrements by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 2(size of an int) and
the new address it will points to 998. While if a float type pointer is decremented then it will decrement by
4(size of a float) and the new address will be 996.
Assume that float takes 4 bytes, predict the output of following program.
#include <stdio.h>
int main()
{
float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
float *ptr1 = &arr[0];
float *ptr2 = ptr1 + 3;
return 0;
}
Output: 90.500000 3
GAURAV BHATIA
5
The pointer variable ptr is allocated memory address 8000 and it holds the address of the stringvariable
str i.e., 1000.
Output:
Iran
Iraq
// pointer to string
#include <stdio.h>
#include <string.h>
void function(char**);
int main()
{
char *str = "Pointer-to-string";int
i, j = strlen(str);
GAURAV BHATIA
6
printf("%c",
*str++);return 0;
}
Output: Pointer-to-string
GAURAV BHATIA
7
To print the cities:
int r, c;
// print cities
= 0;
while(*(cityPtr[r] + c) != '\0') {
c++;
printf("\n");
name {
member1;
member2;
};
void main()
GAURAV BHATIA
8
Access Members of a structure using pointers
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person = person1; //person1 is an instance of structure person
struct person *personPtr;
// personPtr is the structure pointers , stores address of person structpersonPtr
= &person1;
printf("Enter age: "); scanf("%d",
&personPtr->age);printf("Enter
weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
}
In this example, the address of person1 is stored in the personPtr pointer using personPtr =
&person1;.
Now, you can access the members of person1 using the personPtr pointer. By the
way,
Output:
Enter age: 12
Enter weight: 34
Displaying:
Age: 12
weight: 34.000000
Algorithm complexity can be further divided into two types: time complexity and space complexity
The time complexity, as the name suggests, refers to the time taken by the algorithm to
complete its execution.
The space complexity refers to the memory occupied by the algorithm.
Time Complexity?
Time Complexity of an algorithm/program is not the measure of actual time taken for the program to be
executed, rather it is the number of times each statement of the logic gets executed to produce the required
output.
Θ Notation: The theta notation bounds a function from above and below, so it defines exact asymptotic
behavior.
Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds afunction
only from above.
O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 <= f(n) <= c*g(n) forall n >=
n0}
Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ωnotation
provides an asymptotic lower bound.
Ω (g(n)) = {f(n): there exist positive constants c and n0 such that 0 <= c*g(n) <= f(n) for
all n >= n0}.
But most times, we will use the Big O notation because it will give us an upper limit of the
execution time i.e. the execution time in the worst-case inputs. Also, an algorithm's running time
may vary among different inputs of the same size, and hence we consider worst-case complexity,
which is the maximum amount of time required for inputs of a given size.
GAURAV BHATIA
10
Asymptotic analysis
Asymptotic analysis of an algorithm, refers to defining the mathematical boundation/framing of its run-time
performance. Using asymptotic analysis, we can very well conclude the best case, average case and worst
case scenario of an algorithm.
Asymptotic analysis can provide three levels of mathematical binding of execution time of an algorithm −
GAURAV BHATIA
11
Example: #include <stdio.h>int
main()
{
int a = 4;
int b = 6;
int c;
c = a + b;
printf(%d, c);
}
Complexity is O(1). No loop only simple statements, these are executed only once.
GAURAV BHATIA
12
GAURAV BHATIA
13
1.7 Recursion
The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite
easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree
Traversals, DFS of Graph, etc.
GAURAV BHATIA
14
during the execution of a program.
Call by Reference: The pointers are used to pass a reference of a variable to other function.
Data Structures like a tree, graph, linked list, etc.: The pointers are used to construct different
data structures like tree, graph, linked list, etc.
8 What Is Indirection?
Answer: If you declare a variable, its name is a direct reference to its value. If you have a pointer to a
variable or any other object in memory, you have an indirect reference to its value.
GAURAV BHATIA
15
pointers that do not have any data type associated with them. Void pointers can contain the address of any
type of variable. So, the data type that a void pointer points to can be anything.
if ( p )
{
/*Run when valid address */
}
else
{
/*When NULL pointer*/
}
13 Differentiate Between Arrays And Pointers?
Answer: Pointers are used to manipulate data using the address. Pointers use * operator to access
the data pointed to by them Arrays use subscripted variables to access and manipulate data. Array
variables can be equivalently written using pointer expression.
GAURAV BHATIA
16
16 Difference between an array of pointers and a pointer to an array
Answer:
Array of pointers
Declaration is: data_type *array_name[size];Size
represents the row size.
The space for columns may be dynamically
Pointers to an array
Declaration is data_type ( *array_name)[size];Size
represents the column size.
#include <stdio.h>
int main(void)
{
int aiData[5] = {100,200,300,400,500};
int *piData = &aiData;
++*piData;
printf("%d %d %d \n ”, aiData[0], aiData[1], *piData);
printf("%d”, *(piData+2));
return 0;
}
Output: 101 200 101
300
18 What are the advantages of using array of pointers to string instead of an array of strings?
Answer:
GAURAV BHATIA
17
21 How memory is allocated to different function calls in recursion?
When any function is called from main(), the memory is allocated to it on the stack. A recursive
function calls itself, the memory for a called function is allocated on top of memory allocated to
calling function and different copy of local variables is created for each function call. When the
base case is reached, the function returns its value to the function by whom it is called and
memory is de-allocated and the process continues.
22 What are the disadvantages of recursive programming over iterative programming?
Answer: The recursive program has greater space requirements than iterative program as all functions
will remain in the stack until the base case is reached. It also has greater time requirements because of
function calls and returns overhead.
GAURAV BHATIA
18
Essential Quiz 1- ESSENTIALS OF DATA STRUCTURE
int fun(int n)
{
if (n == 4)
return n;
else return 2*fun(n+1);
}
int main()
{
printf("%d ", fun(2));
return 0;
}
(A) 4
(B) 8
(C) 16
(D) Runtime error
Answer: C
main()
void *q=p;
char *r=q;
printf("%c",*r);
A - Garbage character.
B-A
C - 65
D - Compile error
Answer: B
19
3. What is the output of the following program?
#include<stdio.h>
main()
printf("%d", p[1]);
A-1
B-2
C - Compile error
D - Runtime error
Answer: B
4. Consider the following recursive function fun(x, y). What is the value of fun(4, 3)
(A) 11001
(B) 10011
(C) 11111
(D) 00000
Answer: B
20
6. What does the following function do?
int fun(int x, int y)
{
if (y == 0) return 0;
return (x + fun(x, y-1));
}
A. x+y
B. x+x*y
C. x*y
D. xy
Answer: C
Answer: D
GAURAV BHATIA
A. Address Of p
B. Hello
C. H
D. None
Answer: C
13.
int y[4] = {6, 7, 8, 9};
int *ptr = y + 2;
printf("%d\n", ptr[ 1 ] );
A. 6
B. 7
C. 8
D. 9
Answer: D
14. What are the two main measures for the efficiency of an algorithm?
A. Time and memory
B. Time and space
C. Complexity and space
D. Data and memory
Answer: A
15. Let w(n) and A(n) denote respectively, the worst case and average case running time of an
algorithm executed on an input of size n. which of the following is ALWAYS TRUE?
Answer: C
17. What does it mean when we say that an algorithm X is asymptotically more efficient than Y?
A. X will be a better choice for all inputs
B. X will be a better choice for all inputs except possibly small inputs
C. X will be a better choice for all inputs except possibly large inputs
GAURAV BHATIA
D. Y will be a better choice for small inputs.
Answer: B.
int a = 0, b = 0;
= a + rand();
= b + rand();
int main()
{
int y = 20;
fun(&y);
printf("%d", y);
return 0;
}
(A) 20
(B) 30
(C) Compiler error
(D) Runtime error
Answer: B
#include<stdio.h>
int main() {
int a = 10;
void *p = &a;
int *ptr = p;
GAURAV BHATIA
printf(“%u”,*ptr);
return 0;
}
A. 11
B. 10
C. Garbage value
D. None of the above
Answer: B
Essential Quiz 2: ESSENTIALS OF DATA STRUCTURE
int a = 0, i = N;
while (i > 0) {
a += i;i
/= 2;
}
A. O(N)
B. O(Sqrt(N))
C. O(N / 2)
D. O(log N)
Answer: D.
for(var i=0;i<n;i++)
i*=k
A. O(n)
B. O(k)
C. O(logkn)
D. O(lognk)
Answer: C
4. What will be the time complexity of the following code?
var value = 0; for(var
i=0;i<n;i++)
for(var j=0;j<i;j++)
value += 1;
GAURAV BHATIA
A. n
B. (n+1)
C. n(n-1)/2
D. n(n+1)/2
Answer: C
8. Consider the code fragment: int num[] = {24,34,12}; int i = 0; Then, to print the first number
of the array, which of the following statements cannot be used?
A. printf(“%d”, *(num+i));
B. printf(“%d”,*(i+num));
C. printf(“%d”,i[num]);
D. All can be used
Answer: D.
printf(“%d”, *(*(student+i)+j));
A. 56
B. 33
C. 1234
D. 80
GAURAV BHATIA
Answer: A
11.int x = 2, y = 3;
p1 = &x; p2 = &y;
A.p3 =p1+p2;
B.p1++
C.p2--
D.p1+=2
Answer: A
12. How many times is ‘a’ printed when the following C code is executed?
#include<stdio.h>
main()
{
int a;
a=f1(10);
printf("%d",a);
}
f1(int b)
{
if(b==0)
return 0;
else
{
printf("a");
f1(b--);
}
}
a) 9 times
b) 10 times
c) 0 times
d) Infinite number of times
GAURAV BHATIA
Answer: D
return 0;
}
A. 200
B. 50
C. Compiler error
D. Runtime error
Answer: B
15. In the absence of a exit condition in a recursive function, the following error is given
Anwer: A
19. In recursion, the condition for which the function will stop calling itself is
a) Best case
b) Worst case
GAURAV BHATIA
c) Base case
d) There is no such condition
Answer: C
Essential Quiz 3: ESSENTIALS OF DATA STRUCTURE
1.
void fun(int *ptr)
{
printf("%d ", *ptr);
*ptr = 150;
}
int main()
{
int y = 2020;
fun(&y);
printf("%d", y);
return 0;
}
A. 2020 150
B. 150 2020
C. Compiler error
D. 2020 2020
Answer: A
#include<stdio.h>
void main() {
char a = 'A';
char *p = &a;
printf("%d \t",*p);
printf("%c",*p);
}
A. 65 A
B. A A
C. Garbage value
D. None of the above
Answer: A
A. 24
B. 4
C. 12
D. 10
Answer: A
Answer: C
printf("%s",ary);
return 0;
A) D
B) Discovery Channel
C) Discovery
D) Compiler error
Answer: B
GAURAV BHATIA
9. What is the output of the code?
int main()
{
char country[]="INDIA";
char *ptr;
ptr = country;
while(*ptr != '\0')
{
printf("%c", *ptr);
ptr++;
}
return 0;
}
A) I
B) INDIA
C) Compiler error
D) NDIA
Answer: B
A) ANT
B) GOAT
C) G
D) A
Answer: B
A) NT
B) OAT
GAURAV BHATIA
C) ANT
D) Compiler error
Answer: A
i=2;
while(p[i] != '\0')
printf("%c",*(p+i));
i++;
A. izProgram
B. QuizProgram
C. Compiler error
D. zProgram
Answer: A
GAURAV BHATIA
Number of bytes between two pointers are: 10
C. Number of elements between two pointer are:0
Number of bytes between two pointers are: 12
15. .
void fun(int *ptr)*ptr = 150 + 10;
{
}
int main()
{
int y = 2020;
fun(&y);
printf("%d", y);
return 0;
}
A. 160
B. Compiler error
C. Address of y incremented by 10
D. None of the above
Answer: A
char *p =c;
IMS2011-2021
(B) T2011-2021
(C) 2011-2021
(D) 2021
GAURAV BHATIA
Answer: A
17. main( )
{
static int a[ ] = { 0, 1, 2, 3, 4 } ;
static int *p[ ] = { a, a + 1, a + 2, a + 3, a+ 4 } ;int
**ptr = p ;
ptr++ ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr ) ;
*ptr++ ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr ) ;
**ptr++ ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr ) ;
++*ptr ;
printf ( “%d %d %d\n”, ptr - p, *ptr - a, **ptr )
}
Answer: B
18. main( )
{
static int a[ ] = { 2, 4, 6, 8, 10 } ;
int i ;
for ( i = 0 ; i <= 4 ; i++ )
{
*( a + i ) = a[i] + i[a] ;
printf ( “%d”, *(i + a ) ) ;
}
}
A. 2 4 6 8 10
B. 4 8 12 16 20
C. 2 8 12 16 20
D. 4 8 6 16 20
Answer: B
Answer: C
19. main( )
{
static int b[ ] = { 10, 20, 30, 40, 50 } ;
int i, *k ;
k = &b[4] – 4 ;
for ( i = 0 ; i <= 4 ; i++ )
GAURAV BHATIA
{
printf ( “%d”, *k ) ;
k++ ;
}
}
A. 10 20 30 40 50
B. 50 40 30 20 10
C. 10 30 50 20 40
D. 10 10 10 10 10
Answer: A
20. #include<string.h>
main ( )
{
char str1[15]= “Good” ;
char str2[ ] = “Evening” ;
strcpy (str1, str2) ;
printf ( “%s\n”, str1 ) ;
}
A. Evening
B. GoodEvening
C. Good
D. GoodE
Answer: A
GAURAV BHATIA
Linked List is the collection of randomly stored data objects called nodes. In Linked List, each nodeis linked
to its adjacent node through a pointer. A node contains two fields, i.e. Data Field and Link Field. Each node
element has two parts:
a data field
a reference (or pointer) to the next node.
The first node in a linked list is called the head and the last node in the list has the pointer to NULL. Null in
the reference field indicates that the node is the last node. When the list is empty, the head isa null reference.
GAURAV BHATIA
2.2 Doubly Linked List
What is a doubly-linked list (DLL)? What are its applications.
Answer:
The doubly linked list is a complex type of linked list in which a node contains a pointer to the previous
as well as the next node in the sequence. In a doubly linked list, a node consists of threeparts:
o node data
o pointer to the next node in sequence (next pointer)
o pointer to the previous node (previous pointer).
A music playlist with next song and previous song navigation options.The
The undo and redo functionality on platforms such as word, paint etc, where you can reverse thenode to
get to the previous page.
What is the use of a doubly-linked list when compared to that of a singly linked list?
GAURAV BHATIA
In a singly linked list, we have only forward links. Hence, we cannot traverse the linked list in a backward
manner. In order to overcome this, we go for a doubly linked list. In a doubly linked list, each node has three
fields such as previous, data and next field and has two links such as a forward and backward link. The
previous field of the first node and the address field of the last node is NULL. The previous field of the second
node has the address of the first node and so on.
Also, accessing of elements can be done more efficiently in case of a doubly linked list.
1) Any node can be a starting point. We can traverse the whole list by starting from any point. We
just need to stop when the first visited node is visited again.
2) Useful for implementation of queue. Unlike this implementation, we don’t need to maintain two
pointers for front and rear if we use circular linked list. We can maintain a pointer to the last inserted
node and front can always be obtained as next of last.
3) Circular lists are useful in applications to repeatedly go around the list. For example, when multiple
applications are running on a PC, it is common for the operating system to put the running
applications on a list and then to cycle through them, giving each of them a slice of time to execute,
and then making them wait while the CPU is given to another application. It is convenient for the
operating system to use a circular list so that when it reaches the end of the list it can cycle around to
the front of the list.
GAURAV BHATIA
Used in managing the computing resources of a computer.
Implementing stacks and queues.
Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two
consecutive elements are linked or connected by previous and next pointer and the last node points to first
node by next pointer and also the first node points to last node by previous pointer.
struct node
int data;
};
GAURAV BHATIA
How Memory is managed in Circular Doubly linked list
The variable head contains the address of the first element of the list i.e. 1 hence the starting node of the list
contains data A is stored at address 1. Since, each node of the list is supposed to have three parts therefore,
the starting node of the list contains address of the last node i.e. 8 and the next node
i.e. 4. The last node of the list that is stored at address 8 and containing data as 6, contains address ofthe first
node of the list as shown in the image.
GAURAV BHATIA
Insertion in empty circular doubly list
To insert a node at the beginning of the list, create a node(Say T) with data = 5, T next pointer points to first
node of the list, T previous pointer points to last node the list, last node’s next pointer points to this T node,
first node’s previous pointer also points this T node and at last don’t forgetto shift ‘Start’ pointer to this T
node.
List can be traversed from both the directions i.e. from head to tail or from tail to head.
Jumping from head to tail or from tail to head is done in constant time O(1).
Circular Doubly Linked Lists are used for implementation of advanced data structures
like Fibonacci Heap.
GAURAV BHATIA
Applications of Circular doubly linked list
Managing songs playlist in media player applications.
Managing shopping cart in online shopping.
GAURAV BHATIA
Short Type Questions
1 Are linked lists of linear or non-linear type?
Answer:
A linked list is considered both linear and non-linear data structure depending upon the situation.
Insertion and deletion process is expensive in an array as the room has to be created for the newelements
and existing elements must be shifted.
But in a linked list, the same operation is an easier process, as we only update the address present inthe next
pointer of a node.
Linked list is a dynamic data structure that means there is no need to give an initial size at the timeof
creation as it can grow and shrink at runtime by allocating and deallocating memory.
Whereas, the size of an array is limited as the number of items is statically stored in the main
memory.
No wastage of memory
As the size of a linked list can grow or shrink based on the needs of the program, there is nomemory
wasted because it is allocated in runtime.
In arrays, if we declare an array of size 10 and store only 3 elements in it, then the space for 3
elements is wasted. Hence, chances of memory wastage is more in arrays.
GAURAV BHATIA
3 How many pointers are necessary to implement a simple Linked List?
Answer: There are generally three types of pointers required to implement a simple linked list:
o A 'head' pointer which is used for pointing to the start of the record in a list.
o A 'tail' pointer which is used for pointing to the last node. The key factor in the last node is
that its subsequent pointer points to nothing (NULL).
o A pointer in every node which is used for pointing to the next node element.
How can you insert a node to the beginning of a singly linked list?
To insert the node to the beginning of the list, we need to follow these steps:
Node *head;
voidInsertNodeAtFront(int data)
{
/* 1. create the new node*/
Node *temp = new Node;
temp->datadata = data;
/* 2. insert it at the first position*/
[Type text]
temp->next = head;
/* 3. update head to point to this new node*/
. head = temp;
.}
Answer: The following are the basic operations supported by linked lists.
struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node));
Answer: Doubly linked list nodes consist of three fields: an integer value and two links pointing to two
other nodes (one to the last node and another to the next node).
On the other hand, a singly linked list consists of a link which points only to the next node.
Answer: To reverse the singly linked list, we are required to iterate through the list. We need to reverse the
link at each step like after the first iteration, the head will point to null, and the next element will point to the
head. At the end of traversal when we reach the tail of the linked list, the tail will start pointing to the second
last element and will become a new head. It is because we can further traverse through all the elements from
that particular node.
11 The steps given below can be used to reverse a singly linked list:
o First, we need to set a pointer (*current) pointing to the first node (i.e., current=head).
o Move ahead until current! =null (till the end of the list).
GAURAV BHATIA
o Set another pointer (*next) pointing to the next node (i.e. next=current->next>next=result
o Keep reference of *next in a temporary variable (*result) i.e. current->next=result
o Exchange the result value with current, i.e., result=current
o And then swap the current value with next, I.e., current=next.
o Return result and repeat from step 2.
A linked list can also be reversed by using recursion which eliminates the use of a temporary variable.
Answer: We can iterate over the linked list and keep a count of nodes until we reach the end of the linked
list where the next node will be null. The value of the counter is considered as the length of the linked list.
13 How can someone display singly linked list from first to last?
Answer: One must follow these steps to display singly linked list from first to last:
Answer: Some of the important drawbacks of the linked list are given below:
o Random access is not allowed. We need to access elements sequentially starting from the first
node. So we cannot perform a binary search with linked lists.
o More memory space for a pointer is required with each element of the list.
GAURAV BHATIA
o Slow O(n) index access, since accessing linked list by index means we have to loop over the
list recursively.
o Poor locality, the memory used for the linked list is scattered around in a mess.
Answer: Simple Insertion sort is easily adabtable to singly linked lists. To insert an element, the linked list
is traversed until the proper position is found, or until the end of the list is reached. It is inserted into the list
by merely adjusting the pointers without shifting any elements, unlike in the array. This reduces the time
required for insertion but not the time required for searching for the proper position.
Answer: No, we cannot apply the binary search algorithm to a sorted linked list because finding theindex of
the middle element is difficult.
How to reverse a singly linked list (Iterative approach)
Answer:
Answer:
Time and Space complexity of List and Array for different operations
GAURAV BHATIA
18 How is an Array different from Linked List?
Answer:
The size of the arrays is fixed, Linked Lists are Dynamic in size.
Inserting and deleting a new element in an array of elements is expensive, Whereas both
insertion and deletion can easily be done in Linked Lists.
Random access is not allowed in Linked Listed.
Extra memory space for a pointer is required with each element of the Linked list.
Arrays have better cache locality that can make a pretty big difference in performance
GAURAV BHATIA
Insertion/deletion at the beginning O(1) O(n)
GAURAV BHATIA
Essential Quiz 1 for Topic 2
Answer: A
2. The advantage of ...................... is that they solve the problem if sequential storage
representation. But disadvantage in that is they are sequential lists.
A) Lists
B) Linked Lists
C) Trees
D) Queues
Answer: B
Answer: B
4. A linear collection of data elements where the linear node is given by means of pointer is
called?
a) Linked list
b) Node list
c) Primitive list
d) None
Answer:A
5. Which of the following operations is performed more efficiently by doubly linked list than
by singly linked list?
Answer: A
GAURAV BHATIA
Q Consider an implementation of unsorted singly linked list. Suppose it has its representation with a
head and tail pointer. Given the representation, which of the following operation can be
implemented in O(1) time?
a) I and II
b) I and III
c) I,II and III
d) I,II and IV
Answer: C
6. Consider an implementation of unsorted singly linked list. Suppose it has its representation
with a head pointer only. Given the representation, which of the following operation can be
implemented in O(1) time?
a) I and II
b) I and III
c) I,II and III
d) I,II and IV
Answer: B
7. In linked list each node contain minimum of two fields. One field is data field to store the
data second field is?
a) Pointer to character
b) Pointer to integer
c) Pointer to node
d) Node
Answer:C
8. What would be the asymptotic time complexity to add a node at the end of singly linked
list, if the pointer is initially pointing to the head of the list?
GAURAV BHATIA
a) O(1)
b) O(n)
c) θ (n)
d) θ (1)
Answer:C
9. What would be the asymptotic time complexity to add an element in the linked list?
a) O(1)
b) O(n)
c) O(n2)
d) None
Answer: B
10. What would be the asymptotic time complexity to find an element in the linked list?
a) O(1)
b) O(n)
c) O(n2)
d) None
Answer: B
11. What would be the asymptotic time complexity to insert an element at the second position
in the linked list?
a) O(1)
b) O(n)
c) O(n2)
d) None
Answer: A
12. The concatenation of two list can performed in O(1) time. Which of the following
variation of linked list can be used?
Answer: C
GAURAV BHATIA
13. A variant of linked list in which last node of list, points to the first node of the list is?
Answer: C
Answer: C
15. What kind of linked list is best to answer question like “What is the item at position n?”
Answer: D
16. A variation of linked list is circular linked list, in which the last node in the list points to
first node of the list. One problem with this type of list is?
a) It waste memory space since the pointer head already points to the first node and thus the list
node does not need to point to the first node.
b) It is not possible to add a node at the end of the list.
c) It is difficult to traverse the list as the pointer of the last node is now not NULL
d) All of above
Answer: C
a) One pointer
b) Two pointer
c) Three pointer
d) None
Answer: B
GAURAV BHATIA
18. What is the second part of a node in a linked list that contains the address of the next node
called?
A. data
B. pointer
C. element
D. Link
Answer: D
GAURAV BHATIA
Essential Quiz 2 for Topic 2
1. The time required to delete a node x from a doubly linked list having n nodes is
a. O (n)
b. O (log n)
c. O (1)
d. O (n log n)
Answer:: C
a) Insertion sort
b) Radix sort
c) Polynomial manipulation
d) Binary search
Answer : D.
a) list
c) skip list
d) none
Answer : B
d) none Answer : c
GAURAV BHATIA
6. Linked list is generally considered as an example of type of memory allocation.
A. Static
B. Compile time
C. Dynamic
D. None of these
Answer: C
7. Each Node contain minimum two fields one field called data field to store data. Another field is
of type .
A. Pointer to character
B. Pointer to class
C. Pointer to integer
D. Pointer to Node
Answer: D
8. Which of the following statement is not true about the doubly linked list?
Answer: c
9. What is the output of following function for start pointing to first node of following linked list?
1->2->3->4->5->6
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
A. 1 4 6 6 4 1
B. 1 3 5 1 3 5
GAURAV BHATIA
C. 1 2 3 5
D. 1 3 5 5 3 1
Answer: D
10. Given pointer to a node X in a singly linked list. Only one pointer is given, pointer to head node
is not given, can we delete the node X from given linked list?
A. underflow
B. Overflow
C. Null linked list
D. saturated
Answer: C
Answer: D
14. Consider a linked list of n elements. What is the time taken to insert an element after element
pointed by same pointer ?
A. O(n)
B. O(log n)
GAURAV BHATIA
C. O(n-1)
D. D.O(1)
E. Answer: D
15. Time require to find any element of the linked list is .
A. O(n)
B. O(1)
C. O(n^2)
D. none of these
Answer: A
16. Consider the below representation and predict what will be printed on the screen by following
statement ?
start->next->data
struct node {
int data;
}*start = NULL;
17. 17.
Consider the following linked list and linked list representation. what will be the value of following
statement ?
start->next->next->next->data
struct node {
int data;
}*start = NULL;
GAURAV BHATIA
A. 12
B. 30
C. 15
D. 25
Answer: D
18. Consider the following linked list and linked list representation. what will be the value of
following statement ?
start->next->next->datastruct
node {
int data;
}*start = NULL;
A. 10
B. 5000
C. 5
D. 3000
Answer: C
19. How many nodes will ListSearch visit when searching for 93?
A. 4
B. 3
C. 2
GAURAV BHATIA
D. 1
Answer: B
20. What is value in the head -> next -> next ->next-> data below?
A. 17
B. 93
C. 77
D. 31
Answer: A
GAURAV BHATIA
Topic 3: STACK
STACK
one end, called TOP of the stack. The elements are removed in reverse order of that in which
they were inserted into the stack.
2.2 STACK
OPERATIONS
There are two ways to represent Stack in memory. One is using array and other is using linked
list.
Usually, the stacks are represented in the computer by a linear array. In the following
algorithms/procedures of pushing and popping an item from the stacks, we have
considered, a linear array STACK, a variable TOP which contain the location of the
top element of the stack; and a variable STACKSIZE which gives the maximum
GAURAV BHATIA
number of elements that can be hold by the stack
Push Operation
Push an item onto the top of the stack (insert an item)
GAURAV BHATIA
Here are the minimal operations we'd need for an abstract stack (and their typical
names):
Stacks are used by compilers to help in the process of converting infix to postfix
arithmetic expressions and also evaluating arithmetic expressions. Arithmetic
expressions consisting variables, constants, arithmetic operators and parentheses.
Humans generally write expressions in which the operator is written between the
operands (3 + 4, for example). This is called infix notation. Computers “prefer”
postfix notation in which the operator is written to the right of two operands. The
preceding infix expression would appear in postfix notation as 3 4 +. To evaluate a
complex infix expression, a compiler would first convert the expression to postfix
notation, and then evaluate the postfix version of the expression. We use the
following three levels of precedence for the five binary operations.
112
For example:
(66 + 2) * 5 – 567 / 42
to postfix
66 22 + 5 * 567 42 / –
The following algorithm transforms the infix expression Q into its equivalent
postfix expression
P. It uses a stack to temporary hold the operators and left parenthesis. The
postfix expression will be constructed from left to right using operands from
Q and operators popped from STACK.
A+( B * C – ( D / E ^ F ) * G ) * H )
113
EVALUATION OF POSTFIX EXPRESSION
If P is an arithmetic expression written in postfix notation. This algorithm uses STACK to hold
operands, and evaluate. For example:
(5 + 2) * 3 – 9 / 3
And its postfix is:
52+3*93/–
114
115
2.6 RECURSION
Recursion is a programming technique that allows the programmer to express operations in
terms of themselves. In C, this takes the form of a function that calls itself. A useful way to think of recursive
functions is to imagine them as a process being performed where one of the instructions is to "repeat the
process". This makes it sound very similar to a loop because it repeats the same code, and in some ways, it is
similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the
recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes
be completed without the recursive call. One simpleexample is the idea of building a wall that is ten feet high;
if I want to build a ten-foot-high wall, andthen I will first build a 9-foot-high wall, and then add an extra foot
of bricks. Conceptually, this is like saying the "build wall" function takes a height and if that height is greater
than one, first calls itself to build a lower wall, and then adds one a foot of bricks.
int main()
{
return 0;
}
This program will not continue forever, however. The computer keeps function calls on a stack and once too
many are called without ending, the program will crash. Why not write a program to see how many times the
function is called before the program terminates?
Aquick example:
void count_to_ten ( int count )
{
/* we only keep counting if we have a value less than ten if ( count < 10 )
{
116
count_to_ten( count + 1 );
}
}
int main()
{
count_to_ten ( 0 );
}
117
Short Type Question
1. What is a Stack ?
A stack is a non-primitive linear data structure and is an ordered collection of homogeneous data
elements.The other name of stack is Last-in -First-out list.
One of the most useful concepts and frequently used data structure of variable size for problem
solving is the stack.
7. Define recursion?
It is a technique and it can be defined as any function that calls itself is called recursion. There are
some applications which are suitable for only recursion such as, tower of Hanoi, binary tree traversals etc,
can be implementing very easily and efficiently.
118
8. Which data structures are used for BFS and DFS of a graph?
Queue is used for BFS
Stack is used for DFS. DFS can also be implemented using recursion (Note that
recursion also uses function call stack).
Size of the stack keeps on changing as we insert and delete the element
Stack can store elements of different data type
10. Which data structure is ideal to perform recursion operation and why?
Stack is the most ideal for recursion operation. This is mainly because of its LIFO (Last In First Out)
property, it remembers the elements & their positions, so it exactly knows which one to return when a
function is called.
12. Convert the below given expression to its equivalent Prefix And Postfix notations. ((A +
B) * C - (D - E) ^ (F + G))
Prefix Notation: ^ * +ABC DE + FG Postfix Notation: AB + C * DE FG + ^
119
Condition: None of the stack should indicate an overflow until every slot of an array is used.Yes, 2
stacks can be implemented for the given condition
Start 1st stack from left (1st position of an array) and 2nd from right (last position say n). Move 1ststack
towards right(i.e 1,2,3 ...n) and 2nd towards left (i.e n,n-1,n-2...1).
16. Why and when should I use Stack or Queue data structures instead of Arrays/Lists?
Because they help manage your data in more a particular way than arrays and lists. It means that
when you're debugging a problem, you won't have to wonder if someone randomly inserted an
element into the middle of your list, messing up some invariants.
Arrays and lists are random access. They are very flexible and also easily corruptible. If you want tomanage
your data as FIFO or LIFO it's best to use those, already implemented, collections.
Use a queue when you want to get things out in the order that you put them in (FIFO)
Use a stack when you want to get things out in the reverse order than you put them in (LIFO)
Use a list when you want to get anything out, regardless of when you put them in (and when
you don't want them to automatically be removed).
To add an item at the head, simply push the item onto the stack.
To remove from the head, pop from the stack.
To insert into the middle somewhere, pop items from the "list" stack and push them onto the
temporary stack until you get to your insertion point. Push the new item onto the "list" stack,
then pop from the temporary stack and push back onto the "list" stack. Deletion of an arbitrary
node is similar.
18. Explain the Concept of a Stack. How can you Differentiate it from a Queue?
A stack is a type of linear structure which is used to access components that support the LIFO (LastIn First
Out) method. Push and Pop are key stack functions. Unlike a queue, the arrays and linked lists are used to
enforce a stack.
The element most recently added is removed first in a stack. However, in the event of a queue, theelement
least recently added is removed first.
19. Explain the Steps Involved in the Insertion and Deletion of an Element in the Stack.
120
Algorithms of Stack operations :
Algorithms of PUSH operations-
Step 1: Start
Step 2: Checks if the stack is full if(top==(SIZE-1))
Step 3: If the stack is full, Give a message and exit printf("\nStack Overflow");Step 4:
If the stack is not full, increment top to point next empty space. top=top+1;
Step 5: Add data element to the stack location, where top is pointing.
printf("\nEnter the item to be pushed in stack:"); stack[top]=item; Step 6:
Stop
Algorithms of POP operations :
Step 1: Start
Step 2: Checks if the stack is empty if(top==-1)
Step 3: If the stack is empty, Give a message and exit printf(“\nStack Underflow”);Step 4: If
the stack is not empty, Print the element at which top is pointing. printf("\nPopped element is
: %d\n",stack[top]);
Step 5: Decrement top to point previous location .
top=top-1;
Step 6: Stop
An expression in which operators follow the operands is known as postfix expression. The main benefit
of this form is that there is no need to group sub-expressions in parentheses or to consideroperator
precedence.
o Memory Wastage: The space of the array, which is used to store stack elements can be
wasted because it is fixed prior to its usage.
121
o Array Size: There might be situations in which, we may need to extend the stack to insert
more elements if we use an array to implement stack, It will almost be impossible to extend
the array size, therefore deciding the correct array size is always a problem in array
implementation of stack.
122
ESSENTIAL QUIZ 1
1) Stack is useful for implementing
(a) Radix sort
(b) Recursion
(c) Breadth first
(d) Depth first
123
c) Evaluation
d) Pop
6) Pushing an element into stack already having five elements and stack size of 5, then stack
becomes
a) Overflow
b) Crash
c) Underflow
d) User flow
Explanation: In stack data structure, elements are added one by one using push operation. Stackfollows
LIFO Principle i.e. Last In First Out(LIFO).
9) Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
The maximum number of parentheses that appear on the stack AT ANY ONE TIME when the
algorithm analyzes: (()(())(()))?
a) 1
b) 2
c) 3
d) 4 or more
Explanation: In the entire parenthesis balancing method when the incoming token is a left parenthesis it is
pushed into stack. A right parenthesis makes pop operation to delete the elements in stack till we get left
parenthesis as top most element. 3 elements are there in stack before right parentheses comes. Therefore,
maximum number of elements in stack at run time is 3.
124
10) What is the value of the postfix expression 6 3 2 4 + – *?
a) 1
b) 40
c) 74
d) -18
11) Here is an infix expression: 4 + 3*(6*3-12). Suppose that we are using the usual stack
algorithm to convert the expression from infix to postfix notation. The maximum number of
symbols that will appear on the stack AT ONE TIME during the conversion of this expression?
a) 1
b) 2
c) 3
d) 4
12) The postfix form of the expression (A+ B)*(C*D- E)*F / G is?
a) AB+ CD*E – FG /**
b) AB + CD* E – F **G /
c) AB + CD* E – *F *G /
d) AB + CDE * – * F *G /
13) The data structure required to check whether an expression contains a balanced parenthesis is?
a) Stack
b) Queue
c) Array
d) Tree
14) What data structure would you mostly likely see in non recursive implementation of a recursive
algorithm?
a) Linked List
b) Stack
c) Queue
d) Tree
15) The process of accessing data stored in a serial access memory is similar to manipulating data
on a
a) Heap
b) Binary Tree
c) Array
d) Stack
125
c) A*BC+/D
d) ABCD+/*
17) Which data structure is needed to convert infix notation to postfix notation?
a) Branch
b) Tree
c) Queue
d) Stack
ESSENTIAL QUIZ 2
1) The result of evaluating the postfix expression 5, 4, 6, +, *, 4, 9, 3, /, +, * is?
a) 600
b) 350
c) 650
d) 588
2) Convert the following infix expressions into its equivalent postfix expressions.
(A + B ⋀D)/(E – F)+G
126
a) (A B D ⋀ + E F – / G +)
b) (A B D +⋀ E F – / G +)
c) (A B D ⋀ + E F/- G +)
d) (A B D E F + ⋀ / – G +)
3) Convert the following Infix expression to Postfix form using a stack.
x + y * z + (p * q + r) * s, Follow usual precedence rule and assume that the expression is
legal.
a) xyz*+pq*r+s*+
b) xyz*+pq*r+s+*
c) xyz+*pq*r+s*+
d) xyzp+**qr+s*+
4) Which of the following statement(s) about stack data structure is/are NOT correct?
a) Linked List are used for implementing Stacks
b) Top of the Stack always contain the new node
c) Stack is the FIFO data structure
d) Null link is present in the last node at the bottom of the stack
5) Consider the following operation performed on a stack of size 5.
Push(1);
Pop();
Push(2);
Push(3);
Pop();
Push(4);
Pop();
Pop();
Push(5);
After the completion of all operation, the number of elements present in stack is?a)1
b)2
c) 3
d) 4
127
a) ABCD
b) DCBA
c) DCAB
d) ABDC
9) A normal queue, if implemented using an array of size MAX_SIZE, gets full when?
a) Rear = MAX_SIZE – 1
b) Front = (rear + 1)mod MAX_SIZE
c) Front = rear + 1
d) Rear = front
10) Which of the following real-world scenarios would you associate with a stack data structure?
a) piling up of chairs one above the other
b) people standing in a line to be serviced at a counter
c) offer services based on the priority of the customer
d) tatkal Ticket Booking in IRCTC
11) What does ‘stack underflow’ refer to?
a) accessing item from an undefined stack
b) adding items to a full stack
c) removing items from an empty stack
d) index out of bounds exception
12) What is the time complexity of pop() operation when the stack is implemented using an array?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)
13) Which of the following array position will be occupied by a new element being pushed for a
stack of size N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[1]
d) S[0]
14) What happens when you pop from an empty stack while implementing using the Stack ADT in
Java?
a) Undefined error
b) Compiler displays a warning
c) EmptyStackException is thrown
d) NoStackException is thrown
15) . Array implementation of Stack is not dynamic, which of the following statements supports
this argument?
a) space allocation for array is fixed and cannot be changed during run-time
b) user unable to give the input for stack operations
c) a runtime exception halts execution
d) improper program compilation
16) Which of the following array element will return the top-of-the-stack-element for a stack of
size N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[N-2]
d) S[N+1]
128
17) What is the best case time complexity of deleting a node in a Singly Linked list?
a) O (n)
b) O (n2)
c) O (nlogn)
d) O (1)
18) Which of the following statements are not correct with respect to Singly Linked List(SLL) and
Doubly Linked List(DLL)?
a) Complexity of Insertion and Deletion at known position is O(n) in SLL and O(1) in DLL
b) SLL uses lesser memory per node than DLL
c) DLL has more searching power than SLL
d) Number of node fields in SLL is more than DLL
19) Minimum number of queues to implement stack is
a) 3
b) 4
c) 1
d) 2
20) Which one of the following is an application of Stack Data Structure?
a) Managing function Call
b) Stock Span Problem
c) Arithmetic expression evaluation
d) All of the above
ESSENTIAL QUIZ 3
129
1) Minimum number of queues to implement stack is
a) 3
b) 4
c) 1
d) 2
2) What should be done when a left parenthesis '(' is encountered?
a) Ignored
b) Placed in the output
c) Placed onto operator stack
d) Nothing
3) When an operand is read, which of the following is done?
a) Ignored
b) Placed in the output
c) Placed onto operator stack
d) Nothing
4) Which of the following is an infix expression?
a) (a+b)*(c+d)
b) ab+c*
c) +ab*c
d) *ab
5) What is the time complexity of an infix to postfix conversion algorithm?
a) O(nlogn)
b) O(n)
c) O(logn)
d) O(nm)
6) Parentheses are simply ignored in the conversion of infix to postfix expression.
a) True
b) False
c) Depends on question
d) None of these
7) It is easier for a computer to process a postfix expression than an infix expression.
a) False
b) True
8) What is the postfix expression for the infix expression?
a)-ab-c
b) -a-bc
c) -abc-
d)-abc
9) What is the postfix expression for the following infix expression?
a/b^c-d
a) abc^/d-
b) abc/^d-
130
c) ab^c/d-
d) None of these
10) Which of the following statement is incorrect with respect to infix to postfix conversion
algorithm?
a) operand is always placed in the output
b) operator is placed in the stack when the stack operator has lower precedence
c) parenthesis is included in the output
d) higher and equal priority operators follow the same condition
11) In infix to postfix conversion algorithm, the operators are associated from?
a) R to L
b) L to R
c) mid to L
d) mid to R
12) What is the corresponding postfix expression for the given infix expression?
a*(b+c)/d
a) ab*+cd/
b) ab+*cd/
c) abc*+/d
d) abc+*d/
13) What would be the Prefix notation and Postfix notation for the given equation?
a) ++ABC and AB+C+
b) AB+C+ and ++ABC
c) ABC++ and AB+C+
d) ABC+ and ABC+
14) What would be the Prefix notation for the given equation?
a|b&c
a) a|&bc
b) &|abc
c) |a&bc
d) ab&|c
15) Out of the following operators (|, *, +, &, $), the one having lowest priority is
a) +
b) $
131
c) |
d) &
17) How many stacks are required for applying evaluation of infix expression
algorithm?
a) 1
b) 2
c) 3
d) 4
18) How many passes does the evaluation of infix expression algorithm makes
through the input?
a) 1
b) 2
c) 3
d) 4
19. Evaluate the following statement using infix evaluation algorithm and choose
the correct answer. 1+2*3-2
a) 3
b) 6
c) 5
d) 4
132
133