0% found this document useful (0 votes)
19 views60 pages

DS Unit 1 IQ

The document outlines important questions and concepts related to Data Structures for AKTU Unit-1, including definitions, classifications, and comparisons of linear and non-linear data structures. It explains algorithm complexity using asymptotic notations such as Big O, Omega, and Theta, along with their properties. Additionally, it covers the merits and demerits of arrays, time and space complexity, and methods for calculating addresses in arrays using row-major and column-major order.

Uploaded by

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

DS Unit 1 IQ

The document outlines important questions and concepts related to Data Structures for AKTU Unit-1, including definitions, classifications, and comparisons of linear and non-linear data structures. It explains algorithm complexity using asymptotic notations such as Big O, Omega, and Theta, along with their properties. Additionally, it covers the merits and demerits of arrays, time and space complexity, and methods for calculating addresses in arrays using row-major and column-major order.

Uploaded by

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

lOMoARcPSD|17918814

DATA STRUCTURES AKTU UNIT-1 IMPORTANT


QUESTIONS
data structure (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by pooja Goel (poojagoel2441994@gmail.com)
lOMoARcPSD|17918814

DS UNIT-1

1.1-Define the term Data Structure. List some linear and non-linear data
structures stating the application area where they will be used

Ans: AKTU 2014-15,2015-16, Marks 05

Data structure?

A data structure is a technique of storing and organizing the data in such a way that the
data can be utilized in an efficient manner.. A data structure is classified into two
categories:

o Linear data structure


o Non-linear data structure

Now let's have a brief look at both these data structures.

What is the Linear data structure?

A linear data structure is a structure in which the elements are stored sequentially, and
the elements are connected to the previous and the next element. As the elements are
stored sequentially, so they can be traversed or accessed in a single run. The types of
linear data structures are Array, Queue, Stack, Linked List.

What is a Non-linear data structure?

A non-linear data structure is also another type of data structure in which the data
elements are not arranged in a contiguous manner. As the arrangement is nonsequential,
so the data elements cannot be traversed or accessed in a single run. in the non-linear
data structure, an element can be connected to more than two elements.

Trees and Graphs are the types of non-linear data structure.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

1.2-Difference between Linear and Non-linear Data Structures:


S.NO Linear Data Structure Non-linear Data Structure

In a linear data structure, data elements


are arranged in a linear order where each In a non-linear data structure,
and every element is attached to its data elements are attached in
1. previous and next adjacent. hierarchically manner.

Whereas in non-linear data


In linear data structure, single level is structure, multiple levels are
2. involved. involved.

While its implementation is


Its implementation is easy in comparison complex in comparison to
3. to non-linear data structure. linear data structure.

While in non-linear data


structure, data elements can’t
In linear data structure, data elements be traversed in a single run
4. can be traversed in a single run only. only.

Its examples are: array, stack, queue, While its examples are: trees
5. linked list, etc. and graphs.

Applications of non-linear data


Applications of linear data structures are structures are in Artificial
mainly in application software Intelligence and image
6. development. processing.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Que 1.3- What is complexity of an algorithm ? Explain various notations used to


express the complexity of an algorithm. OR What are the various asymptotic
notations ? Explain Big O notation.

AKTU 2014-15,2015-16,2017-18,2018-19 Marks 07

Ans:

Asymptotic notations are mathematical tools to represent the time complexity of


algorithms for asymptotic analysis.

There are mainly three asymptotic notations:


1. Big-O Notation (O-notation)
2. Omega Notation (Ω-notation)
3. Theta Notation (Θ-notation)

1. Theta Notation (Θ-Notation): Tightly closed notation


It is used for analyzing the average-case complexity of an algorithm.
Let g and f be the function from the set of natural numbers to itself.

Theta notation

Mathematical Representation of Theta notation:


f(n)=Θ (g(n)) if there exist positive constants c1, c2 and n0 such that 0 ≤ c1 * g(n) ≤ f(n) ≤
c2 * g(n) for all n ≥ n0
A simple way to get the Theta notation of an expression is to drop low-order terms and
ignore leading constants. For example, Consider the expression 3n3 + 6n2 + 6000 =
Θ(n3), Examples :
{ 100 , log (2000) , 10^4 } belongs to Θ(1)
{ (n/4) , (2n+3) , (n/100 + log(n)) } belongs to Θ(n)
{ (n^2+n) , (2n^2) , (n^2+log(n))} belongs to Θ( n2)
Note: Θ provides exact bounds.
2. Big-O Notation (O-notation):
Big-O notation represents the upper bound of the running time of an algorithm. Therefore,
it gives the worst-case complexity of an algorithm.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Mathematical Representation of Big-O Notation:


f(n)=O(g(n)), if there exist positive constants c and n0 such that 0 ≤ f(n) ≤ cg(n) for all n ≥
n0 }
Examples :
{ 100 , log (2000) , 10^4 } belongs to O(1)
U { (n/4) , (2n+3) , (n/100 + log(n)) } belongs to O(n)
U { (n^2+n) , (2n^2) , (n^2+log(n))} belongs to O( n^2)
Note: Here, U represents union, we can write it in these manner because O provides
exact or upper bounds .

3. Omega Notation (Ω-Notation):


Omega notation represents the lower bound of the running time of an algorithm. Thus, it
provides the best case complexity of an algorithm.

Mathematical Representation of Omega notation :


f(n)=Ω(g(n)), if there exist positive constants c and n0 such that 0 ≤ cg(n) ≤ f(n) for all n ≥
n0
Examples :
{ (n^2+n) , (2n^2) , (n^2+log(n))} belongs to Ω( n^2)
U { (n/4) , (2n+3) , (n/100 + log(n)) } belongs to Ω(n)
U { 100 , log (2000) , 10^4 } belongs to Ω(1)
Note: Here, U represents union, we can write it in these manner because Ω provides
exact or lower bounds.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Properties of Asymptotic Notations:


1. General Properties:
If f(n) is O(g(n)) then a*f(n) is also O(g(n)), where a is a constant.
Example:
f(n) = 2n²+5 is O(n²)
then, 7*f(n) = 7(2n²+5) = 14n²+35 is also O(n²).
Similarly, this property satisfies both Θ and Ω notation.
We can say,
If f(n) is Θ(g(n)) then a*f(n) is also Θ(g(n)), where a is a constant.
If f(n) is Ω (g(n)) then a*f(n) is also Ω (g(n)), where a is a constant.
2. Transitive Properties:
If f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)).
Example:
If f(n) = n, g(n) = n² and h(n)=n³
n is O(n²) and n² is O(n³) then, n is O(n³)
Similarly, this property satisfies both Θ and Ω notation.
We can say,
If f(n) is Θ(g(n)) and g(n) is Θ(h(n)) then f(n) = Θ(h(n)) .
If f(n) is Ω (g(n)) and g(n) is Ω (h(n)) then f(n) = Ω (h(n))
3. Reflexive Properties:
Reflexive properties are always easy to understand after transitive.
If f(n) is given then f(n) is O(f(n)). Since MAXIMUM VALUE OF f(n) will be f(n) ITSELF!
Hence x = f(n) and y = O(f(n) tie themselves in reflexive relation always.
Example:
f(n) = n² ; O(n²) i.e O(f(n))
Similarly, this property satisfies both Θ and Ω notation.
We can say that,
If f(n) is given then f(n) is Θ(f(n)).
If f(n) is given then f(n) is Ω (f(n)).
4. Symmetric Properties:
If f(n) is Θ(g(n)) then g(n) is Θ(f(n)).
Example:
If(n) = n² and g(n) = n²
then, f(n) = Θ(n²) and g(n) = Θ(n²)
This property only satisfies for Θ notation.
5. Transpose Symmetric Properties:
If f(n) is O(g(n)) then g(n) is Ω (f(n)).
Example:
If(n) = n , g(n) = n²
then n is O(n²) and n² is Ω (n)
This property only satisfies O and Ω notations.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

6. Some More Properties:


1. If f(n) = O(g(n)) and f(n) = Ω(g(n)) then f(n) = Θ(g(n))
2. If f(n) = O(g(n)) and d(n)=O(e(n)) then f(n) + d(n) = O( max( g(n), e(n) ))
Example:
f(n) = n i.e O(n)
d(n) = n² i.e O(n²)
then f(n) + d(n) = n + n² i.e O(n²)
3. If f(n)=O(g(n)) and d(n)=O(e(n)) then f(n) * d(n) = O( g(n) * e(n))
Example:
f(n) = n i.e O(n)
d(n) = n² i.e O(n²)
then f(n) * d(n) = n * n² = n³ i.e O(n³)
_______________________________________________________________________________
Note: If f(n) = O(g(n)) then g(n) = Ω(f(n))

1.4-Rank the following typical bounds in increasing order of growth rate


O(log n), O(n4 ), O(1), O(n2 log n) AKTU 2018-19 Marks 02

Ans:

O(1) < O(log n) < O(n2 log n) < O(n4 )

1.5- Define time complexity and space complexity of an algorithm.

Time Complexity: The time complexity of an algorithm quantifies the amount of time
taken by an algorithm to run as a function of the length of the input. Note that the time
to run is a function of the length of the input and not the actual execution time of the
machine on which the algorithm is running on.

Space Complexity: The space complexity of an algorithm quantifies the amount of


space taken by an algorithm to run as a function of the length of the input

Que 1.6. Write difference between array and linked list. AKTU 2014-15, Marks 05

Ans:

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

1.7-What are the merits and demerits of array data structures ?

Ans:

Array is a linear data structure that is a collection of similar data types. Arrays are
stored in contiguous memory locations. It is a static data structure with a fixed size. It
combines data of similar types.

ARRAY

Applications of Array Data Structure:


Below are some applications of arrays.
 Arrays are used to implement data structures like a stack, queue, etc.
 Arrays are used for matrices and other mathematical implementations.
 Arrays are used in lookup tables in computers.
 Arrays can be used for CPU scheduling.
Advantages of Array:

1. Multiple data items of same type can be declared using same name but
different indexes
2. Accessing an element becomes easy just by using index no.
3. Arrays allocate memory in contiguous memory locations . Hence no extra
memory is allocated.
Disadvantages:

1. Number of elements should be known in advance either declared at run time


by the user or initialized at compile time
2. Insertion and deletion of elements is quite difficult
3. Size of initialized array can not be declared only one time. It can not be
changed again and again.
4. Datatypes of elements should be same
If elements are less than size then extra memory is wasted

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Que 1.8. What is Row and Colom major order ? Explain with an example.

AKTU 2014-15, Marks 05

Ans:

Calculation of address of element of 1-D, 2-D, and 3-D using row-major and
column-major order

Calculating the address of any element In the 1-D array:

A 1-dimensional array (or single-dimension array) is a type of linear array. Accessing its
elements involves a single subscript that can either represent a row or column index.
Example:

2-D array

To find the address of an element in an array the following formula is used-

Address of A[I] = B + W * (I – LB)

I = Subset of element whose address to be found,


B = Base address,
W = Storage size of one element store in any array(in byte),
LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).

Example: Given the base address of an array A[1300 ………… 1900] as 1020 and the
size of each element is 2 bytes in the memory, find the address of A[1700].
Solution:
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Formula used:
Address of A[I] = B + W * (I – LB)
Solution:
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820

Calculate the address of any element in the 2-D array:

The 2-dimensional array can be defined as an array of arrays. The 2-Dimensional arrays
are organized as matrices which can be represented as the collection of rows and
columns as array[M][N] where M is the number of rows and N is the number of
columns.
Example:

2-D array

To find the address of any element in a 2-Dimensional array there are the following
two ways-
1. Row Major Order
2. Column Major Order

1. Row Major Order:


Row major ordering assigns successive elements, moving across the rows and then
down the next row, to successive memory locations. In simple language, the elements of
an array are stored in a Row-Wise fashion.
To find the address of the element using row-major order uses the following formula:

Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))

I = Row Subset of an element whose address to be found,


J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as
zero),
N = Number of column given in the matrix.

Example: Given an array, arr[1………10][1………15] with base value 100 and the size of
each element is 1 Byte in memory. Find the address of arr[8][6] with the help of row-
major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210

2. Column Major Order:


If elements of an array are stored in a column-major fashion means moving across the
column and then to the next column then it’s in column-major order. To find the address
of the element using column-major order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))

I = Row Subset of an element whose address to be found,


J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.

Example: Given an array arr[1………10][1………15] with a base value of 100 and the
size of each element is 1 Byte in memory find the address of arr[8][6] with the help of
column-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Column Subset of an element whose address to be found J = 6


Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157

From the above examples, it can be observed that for the same position two different
address locations are obtained that’s because in row-major order movement is done
across the rows and then down to the next row, and in column-major order, first move
down to the first column and then next column. So both the answers are right.
So it’s all based on the position of the element whose address is to be found for some
cases the same answers is also obtained with row-major order and column-major order
and for some cases, different answers are obtained.
Calculate the address of any element in the 3-D Array:

A 3-Dimensional array is a collection of 2-Dimensional arrays. It is specified by using


three subscripts:
1. Block size
2. Row size
3. Column size
More dimensions in an array mean more data can be stored in that array.

To find the address of any element in 3-Dimensional arrays there are the following two
ways-
 Row Major Order
 Column Major Order

1. Row Major Order:


To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = B + W *(M * N(i-x) + N *(j-y) + (k-z))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Plane

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

y = Lower Bound of Row


z = Lower Bound of Colom

Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of
each element is 2 Bytes in memory find the address of element arr[5][-1][8] with the
help of row-major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 5
Column Subset of an element whose address to be found J = -1
Block Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of row/start row index of matrix x = 1
Lower Limit of column/start column index of matrix y = -4
Lower Limit of blocks in matrix z = 5
M = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N = Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6
Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))
Solution:
Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * ((4 * 6 + 3) * 6 + 3)
= 400 + 2 * (165)
= 730

2. Column Major Order:


To find the address of the element using column-major order, use the following
formula:1
Address of A[i][j][k]= B + W(M * N(i – x) + M *(k – z) + (j – y))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Plane
y = Lower Bound of Row
z = Lower Bound of Colom

Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of
each element is 4 Bytes in memory find the address of element arr[3][3][3] with the
help of column-major order?

Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Base address B = 400


Storage size of one element store in any array(in Byte) W = 4
Lower Limit of row/start row index of matrix x = 1
Lower Limit of column/start column index of matrix y = -5
Lower Limit of blocks in matrix z = -10
M = Upper Bound – Lower Bound + 1 = 5 + 5 + 1 = 11
N = Upper Bound – Lower Bound + 1 = 5 + 10 + 1 = 16
Formula used:
Address of[i][j][k] = B + W(M * N(i – x) + M * (k – z) + (j – y))
Solution:
Address of arr[3][3][3] = 400 + 4 * {[(3 – 1)] * 16 + [3 + 10] ]} * 11 + [3 + 5]
= 400 + 4 * ((32 + 13) * 11 + 8)
= 400 + 4 * (503)
= 400 + 2012
= 2412

Que 1.8. Consider the linear arrays AAA [5 : 50], BBB [– 5 : 10] and CCC [1 : 8].
a.Find the number of elements in each array.

b. Suppose base (AAA) = 300 and w = 4 words per memory cell for AAA.

Find the address of AAA [15], AAA [35] and AAA [55].

AKTU 2015-16, Marks 10

Que 1.9. Suppose multidimensional arrays P and Q are declared as P(– 2: 2, 2: 22)
and Q(1: 8, – 5: 5, – 10 : 5) stored in column major order

i. Find the length of each dimension of P and Q.


ii. The number of elements in P and Q.
iii. Assuming base address (Q) = 400, W = 4, find the effective indices E1 ,
E2 , E3 and address of the element Q[3, 3, 3]. AKTU 2018-19, Marks 07

1.15-Consider a multi-dimensional Array A[90] [30] [40] with base addressstarts


at 1000. Calculate the address of A[10] [20] [30] in row major order and column
major order. Assume the first element is storedat A[2][2][2] and each element
take 2 byte.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

1.16-Suppose multidimensional array P is declared as P( -20:20, 10:35) stored in


Column major order Find the length of each dimension of P and the number of
elements in P . Assume base address 500 , W=1, find the effective address of
P[0][30].

1.17- Explain how sparse matrices are represented in memory. Also explain
upper triangular and lower triangular sparse matrices

Ans:

If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix instead of simple matrix ?
 Storage: There are lesser non-zero elements than zeros and thus lesser memory
can be used to store only those elements.
 Computing time: Computing time can be saved by logically designing a data
structure traversing only non-zero elements..
Example:
00304
00570
00000
02600
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as
zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes
with non-zero elements, we only store non-zero elements. This means storing non-
zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common
representations:
1. Array representation
2. Linked list representation

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Method 1: Using Arrays:


2D array is used to represent a sparse matrix in which there are three rows named as
 Row: Index of row, where non-zero element is located
 Column: Index of column, where non-zero element is located
 Value: Value of the non zero element located at index – (row,column)

Method 2: Using Linked Lists


In linked list, each node has four fields. These four fields are defined as:
 Row: Index of row, where non-zero element is located
 Column: Index of column, where non-zero element is located
 Value: Value of the non zero element located at index – (row,column)
 Next node: Address of the next node

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

1.18-Define Linked List and the various operations on linked list.

Ans:

Linked List

o Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the
pointer which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.

Uses of Linked List

o The list is not required to be contiguously present in the memory. The node can
reside any where in the memory and linked together to make a list. This achieves
optimized utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?

Till now, we were using array data structure to organize the group of elements that are
to be stored individually in the memory. However, Array has several advantages and
disadvantages which must be known in order to decide the data structure which will be
used throughout the program.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Array contains following limitations:

1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to
expand the size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory.
Inserting any element in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array. Using
linked list is useful because,

1. It allocates the memory dynamically. All the nodes of linked list are non-
contiguously stored in the memory and linked together with the help of pointers.
2. Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory spa

Complexity
Data Time Complexity Space
Structure Compleity

Average Worst Worst

Access Search Insertion Deletion Access Search Insertion Deletion

Singly θ(n) θ(n) θ(1) θ(1) O(n) O(n) O(1) O(1) O


Linked List (
n
)

Types of Linked List


Following are the types of linked list

1. Singly Linked List.


2. Doubly Linked List.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

3. Circular Linked List.

Singly Linked List


A Singly-linked list is a collection of nodes linked together in a sequential way where
each node of the singly linked list contains a data field and an address field that
contains the reference of the next node.

The structure of the node in the Singly Linked List is

The nodes are connected to each other in this form where the value of the next
variable of the last node is NULL i.e. next = NULL , which indicates the end of the
linked list.

Doubly Linked List


A Doubly Linked List contains an extra memory to store the address of the previous
node, together with the address of the next node and data which are there in the singly
linked list. So, here we are storing the address of the next as well as the previous
nodes.

The following is the structure of the node in the Doubly Linked List(DLL):

The nodes are connected to each other in this form where the first node has prev =
NULL and the last node has next = NULL .

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Advantages over Singly Linked List-

 It can be traversed both forward and backward direction.


 The delete operation is more efficient if the node to be deleted is given.
( Think! you will get the answer in the second half of this blog)
 The insert operation is more efficient if the node is given before which
insertion should take place. ( Think! )
Disadvantages over Singly Linked List-

 It will require more space as each node has an extra memory to store the
address of the previous node.
 The number of modification increase while doing various operations like
insertion, deletion, etc.

Circular Linked List


A circular linked list is either a singly or doubly linked list in which there are
no NULL values. Here, we can implement the Circular Linked List by making the use of
Singly or Doubly Linked List. In the case of a singly linked list, the next of the last node
contains the address of the first node and in case of a doubly-linked list, the next of
last node contains the address of the first node and prev of the first node contains the
address of the last node.

Advantages of a Circular linked list

 The list can be traversed from any node.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

 Circular lists are the required data structure when we want a list to be accessed
in a circle or loop.
 We can easily traverse to its previous node in a circular linked list, which is not
possible in a singly linked list. ( Think!)
Disadvantages of Circular linked list

 If not traversed carefully, then we could end up in an infinite loop because here
we don't have any NULL value to stop the traversal.
 Operations in a circular linked list are complex as compared to a singly linked
list and doubly linked list like reversing a circular linked list, etc.

Basic Operations on Linked List

 Traversal : To traverse all the nodes one after another.


 Insertion : To add a node at the given position.
 Deletion : To delete a node.
 Searching : To search an element(s) by value.
 Updating : To update a node.
 Sorting: To arrange nodes in a linked list in a specific order.
 Merging: To merge two linked lists into one.
We will see the various implementation of these operations on a singly linked list.

Following is the structure of the node in a linked list:

Linked List Traversal


The idea here is to step through the list from beginning to end. For example , we may
want to print the list or search for a specific node in the list.

The algorithm for traversing a list

 Start with the head of the list. Access the content of the head node if it is not
null.
 Then go to the next node(if exists) and access the node information
 Continue until no more nodes (that is, you have reached the null node)

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Linked List node Insertion


There can be three cases that will occur when we are inserting a node in a linked list.

 Insertion at the beginning


 Insertion at the end. (Append)
 Insertion after a given node
Insertion at the beginning
Since there is no need to find the end of the list. If the list is empty, we make the new
node as the head of the list. Otherwise, we we have to connect the new node to the
current head of the list and make the new node, the head of the list.

Insertion at end

We will traverse the list until we find the last node. Then we insert the new node to
the end of the list. Note that we have to consider special cases such as list being empty.

In case of a list being empty, we will return the updated head of the linked list because
in this case, the inserted node is the first as well as the last node of the linked list.

Insertion after a given node

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

We are given the reference to a node, and the new node is inserted after the given
node.

NOTE: If the address of the prevNode is not given, then you can traverse to that node
by finding the data value.

Linked List node Deletion


To delete a node from a linked list, we need to do these steps

 Find the previous node of the node to be deleted.


 Change the next pointer of the previous node
 Free the memory of the deleted node.
In the deletion, there is a special case in which the first node is deleted. In this, we
need to update the head of the linked list.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Linked List node Searching


To search any value in the linked list, we can traverse the linked list and compares the
value present in the node.

Linked List node Updation


To update the value of the node, we just need to set the data part to the new value.

1.19-Differentiate between overflow and underflow condition in a linked list

Ans:

The underflow and overflow conditions of the linked list are:

Overflow condition:

 This condition is associated with the basic operations on the liked list of inserting an
element in the list.
 We initiate this condition before adding a node to the linked list.
 In the system, this condition happens when there is no vacant memory cell.

Underflow condition:

 This condition is associated with the basic operations on the liked list of deleting an
element in the list.

 We initiate this condition before deleting a node to the linked list.


 If the linked list is empty, this condition occurs to a given linked list for deleting a node.

1.20-List the advantages of doubly linked list over single linked list

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Ans:
Singly Linked List vs Doubly Linked List

Before looking at the differences between the singly linked list and doubly linked list, we
first understand what is singly linked list and doubly linked list separately.

What is a singly linked list?

A singly linked list can be simply called a linked list. A singly linked list is a list that
consists of a collection of nodes, and each node has two parts; one part is the data part,
and another part is the address. The singly linked can also be called a chain as each node
refers to another node through its address part. We can perform various operations on a
singly linked list like insertion, deletion, and traversing.

What is a doubly-linked list?

A doubly linked list is another type of the linked list. It is called a doubly linked list
because it contains two addresses while a singly linked list contains a single address. It is
a list that has total three parts, one is a data part, and others two are the pointers, i.e.,
previous and next. The previous pointer holds the address of the previous node, and the
next pointer holds the address of the next node. Therefore, we can say that list has two
references, i.e., forward and backward reference to traverse in either direction.

Advantages of DLL over the singly linked list:

 A DLL can be traversed in both forward and backward directions.


 The delete operation in DLL is more efficient if a pointer to the node to be deleted
is given.
 We can quickly insert a new node before a given node.
 In a singly linked list, to delete a node, a pointer to the previous node is needed. To
get this previous node, sometimes the list is traversed. In DLL, we can get the
previous node using the previous pointer.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Disadvantages of DLL over the singly linked list:


 Every node of DLL Requires extra space for a previous pointer. It is possible to
implement DLL with a single pointer though (See this and this).
 All operations require an extra pointer previous to be maintained. For example, in
insertion, we need to modify previous pointers together with the next pointers. For
example in the following functions for insertions at different positions, we need 1
or 2 extra steps to set the previous pointer.
.

Que 1.21. What are doubly linked lists ? Write C program to create doubly linked
list. AKTU 2015-16, Marks 10

Ans:

Doubly linked list


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. Therefore, in a doubly linked list, a
node consists of three parts: node data, pointer to the next node in sequence (next
pointer) , pointer to the previous node (previous pointer). A sample node in a doubly
linked list is shown in the figure.

A doubly linked list containing three nodes having numbers from 1 to 3 in their data
part, is shown in the following image.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

In C, structure of a node in doubly linked list can be given as :

1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. }

The prev part of the first node and the next part of the last node will always contain null
indicating end in each direction.

In a singly linked list, we could traverse only in one direction, because each node contains
address of the next node and it doesn't have any record of its previous nodes. However,
doubly linked list overcome this limitation of singly linked list. Due to the fact that, each
node of the list contains the address of its previous node, we can find all the details about
the previous node as well by using the previous address stored inside the previous part
of each node.

Operations on doubly linked list

Node Creation

1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. };
7. struct node *head;

All the remaining operations regarding doubly linked list are described in the following
table.

SN Operation Description

1 Insertion at beginning Adding the node into the linked list at beginning.

2 Insertion at end Adding the node into the linked list to the end.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

3 Insertion after specified Adding the node into the linked list after the specified node.
node

4 Deletion at beginning Removing the node from beginning of the list

5 Deletion at the end Removing the node from end of the list.

6 Deletion of the node Removing the node which is present just after the node containing the given
having given data data.

7 Searching Comparing each node data with the item to be searched and return the
location of the item in the list if the item found else return null.

8 Traversing Visiting each node of the list at least once in order to perform some specific
operation like searching, sorting, display, etc.

Menu Driven Program in C to implement all the operations of doubly linked list
1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. struct node *prev;
6. struct node *next;
7. int data;
8. };
9. struct node *head;
10. void insertion_beginning();
11. void insertion_last();
12. void insertion_specified();
13. void deletion_beginning();
14. void deletion_last();
15. void deletion_specified();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

21. while(choice != 9)
22. {
23. printf("\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\n");
26. printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4
.Delete from Beginning\n
27. 5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.Show\n9.E
xit\n");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. insertion_beginning();
34. break;
35. case 2:
36. insertion_last();
37. break;
38. case 3:
39. insertion_specified();
40. break;
41. case 4:
42. deletion_beginning();
43. break;
44. case 5:
45. deletion_last();
46. break;
47. case 6:
48. deletion_specified();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

56. case 9:
57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void insertion_beginning()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *)malloc(sizeof(struct node));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter Item value");
76. scanf("%d",&item);
77.
78. if(head==NULL)
79. {
80. ptr->next = NULL;
81. ptr->prev=NULL;
82. ptr->data=item;
83. head=ptr;
84. }
85. else
86. {
87. ptr->data=item;
88. ptr->prev=NULL;
89. ptr->next = head;
90. head->prev=ptr;
91. head=ptr;
92. }

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

93. printf("\nNode inserted\n");


94. }
95.
96. }
97. void insertion_last()
98. {
99. struct node *ptr,*temp;
100. int item;
101. ptr = (struct node *) malloc(sizeof(struct node));
102. if(ptr == NULL)
103. {
104. printf("\nOVERFLOW");
105. }
106. else
107. {
108. printf("\nEnter value");
109. scanf("%d",&item);
110. ptr->data=item;
111. if(head == NULL)
112. {
113. ptr->next = NULL;
114. ptr->prev = NULL;
115. head = ptr;
116. }
117. else
118. {
119. temp = head;
120. while(temp->next!=NULL)
121. {
122. temp = temp->next;
123. }
124. temp->next = ptr;
125. ptr ->prev=temp;
126. ptr->next = NULL;
127. }
128.
129. }

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

130. printf("\nnode inserted\n");


131. }
132. void insertion_specified()
133. {
134. struct node *ptr,*temp;
135. int item,loc,i;
136. ptr = (struct node *)malloc(sizeof(struct node));
137. if(ptr == NULL)
138. {
139. printf("\n OVERFLOW");
140. }
141. else
142. {
143. temp=head;
144. printf("Enter the location");
145. scanf("%d",&loc);
146. for(i=0;i<loc;i++)
147. {
148. temp = temp->next;
149. if(temp == NULL)
150. {
151. printf("\n There are less than %d elements", loc);
152. return;
153. }
154. }
155. printf("Enter value");
156. scanf("%d",&item);
157. ptr->data = item;
158. ptr->next = temp->next;
159. ptr -> prev = temp;
160. temp->next = ptr;
161. temp->next->prev=ptr;
162. printf("\nnode inserted\n");
163. }
164. }
165. void deletion_beginning()
166. {

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

167. struct node *ptr;


168. if(head == NULL)
169. {
170. printf("\n UNDERFLOW");
171. }
172. else if(head->next == NULL)
173. {
174. head = NULL;
175. free(head);
176. printf("\nnode deleted\n");
177. }
178. else
179. {
180. ptr = head;
181. head = head -> next;
182. head -> prev = NULL;
183. free(ptr);
184. printf("\nnode deleted\n");
185. }
186.
187. }
188. void deletion_last()
189. {
190. struct node *ptr;
191. if(head == NULL)
192. {
193. printf("\n UNDERFLOW");
194. }
195. else if(head->next == NULL)
196. {
197. head = NULL;
198. free(head);
199. printf("\nnode deleted\n");
200. }
201. else
202. {
203. ptr = head;

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

204. if(ptr->next != NULL)


205. {
206. ptr = ptr -> next;
207. }
208. ptr -> prev -> next = NULL;
209. free(ptr);
210. printf("\nnode deleted\n");
211. }
212. }
213. void deletion_specified()
214. {
215. struct node *ptr, *temp;
216. int val;
217. printf("\n Enter the data after which the node is to be deleted : ");
218. scanf("%d", &val);
219. ptr = head;
220. while(ptr -> data != val)
221. ptr = ptr -> next;
222. if(ptr -> next == NULL)
223. {
224. printf("\nCan't delete\n");
225. }
226. else if(ptr -> next -> next == NULL)
227. {
228. ptr ->next = NULL;
229. }
230. else
231. {
232. temp = ptr -> next;
233. ptr -> next = temp -> next;
234. temp -> next -> prev = ptr;
235. free(temp);
236. printf("\nnode deleted\n");
237. }
238. }
239. void display()
240. {

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

241. struct node *ptr;


242. printf("\n printing values...\n");
243. ptr = head;
244. while(ptr != NULL)
245. {
246. printf("%d\n",ptr->data);
247. ptr=ptr->next;
248. }
249. }
250. void search()
251. {
252. struct node *ptr;
253. int item,i=0,flag;
254. ptr = head;
255. if(ptr == NULL)
256. {
257. printf("\nEmpty List\n");
258. }
259. else
260. {
261. printf("\nEnter item which you want to search?\n");
262. scanf("%d",&item);
263. while (ptr!=NULL)
264. {
265. if(ptr->data == item)
266. {
267. printf("\nitem found at location %d ",i+1);
268. flag=0;
269. break;
270. }
271. else
272. {
273. flag=1;
274. }
275. i++;
276. ptr = ptr -> next;
277. }

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

278. if(flag==1)
279. {
280. printf("\nItem not found\n");
281. }
282. }
283.
284. }

.
Que 1.22. What is meant by circular linked list ? Write circular linked list
operations.

AKTU 2016-17, Marks 15

Ans:

Circular Singly Linked List

The circular linked list is a linked list where all nodes are connected to form a circle. In
a circular linked list, the first node and the last node are connected to each other which
forms a circle. There is no NULL at the end.

There are generally two types of circular linked lists:

 Circular singly linked list: In a circular Singly linked list, the last node of the list
contains a pointer to the first node of the list. We traverse the circular singly linked
list until we reach the same node where we started. The circular singly linked list
has no beginning or end. No null value is present in the next part of any of the
nodes.

Representation of Circular singly linked list

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

 Circular Doubly linked list: 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 the previous and next pointer and the last node points to
the first node by the next pointer and also the first node points to the last node by
the previous pointer.

Representation of circular doubly linked list

Note: We will be using the singly circular linked list to represent the working of the
circular linked list.
Representation of circular linked list:
Circular linked lists are similar to single Linked Lists with the exception of connecting
the last node to the first node.

Example of circular linked list

The above Circular singly linked list can be represented as:


Explanation: In the above program one, two, and three are the node with values 3, 5,
and 9 respectively which are connected in a circular manner as:
 For Node One: The Next pointer stores the address of Node two.
 For Node Two: The Next stores the address of Node three
 For Node Three: The Next points to node one.

Operations on the circular linked list:

We can do some operations on the circular linked list similar to the singly linked list
which are:
1. Insertion

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

2. Deletion

1. Insertion in the circular linked list:

A node can be added in three ways:


1. Insertion at the beginning of the list
2. Insertion at the end of the list
3. Insertion in between the nodes
1) Insertion at the beginning of the list: To insert a node at the beginning of the list,
follow these steps:
 Create a node, say T.
 Make T -> next = last -> next.
 last -> next = T.

Circular linked list before insertion

And then,

Circular linked list after insertion

Time complexity: O(1) to insert a node at the beginning no need to traverse list it
takes constant time

Auxiliary Space: O(1)

2) Insertion at the end of the list: To insert a node at the end of the list, follow these
steps:
 Create a node, say T.
 Make T -> next = last -> next;
 last -> next = T.
 last = T.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Before insertion,

Circular linked list before insertion of node at the end

After insertion,

Circular linked list after insertion of node at the end

Time Complexity: O(1) to insert a node at the end of the list. No need to traverse the
list as we are utilizing the last pointer, hence it takes constant time.

Auxiliary Space: O(1)

3) Insertion in between the nodes: To insert a node in between the two nodes,
follow these steps:
 Create a node, say T.
 Search for the node after which T needs to be inserted, say that node is P.
 Make T -> next = P -> next;
 P -> next = T.
Suppose 12 needs to be inserted after the node has the value 10,

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Circular linked list before insertion

After searching and insertion,

Circular linked list after insertion

Time Complexity: O(N)

Auxiliary Space: O(1)

2. Deletion in a circular linked list:

1) Delete the node only if it is the only node in the circular linked list:
 Free the node’s memory
 The last value should be NULL A node always points to another node, so NULL
assignment is not necessary.
Any node can be set as the starting point.
Nodes are traversed quickly from the first to the last.
2) Deletion of the last node:
 Locate the node before the last node (let it be temp)
 Keep the address of the node next to the last node in temp
 Delete the last memory
 Put temp at the end
3) Delete any node from the circular linked list: We will be given a node and our
task is to delete that node from the circular linked list.

Time Complexity: O(N), Worst case occurs when the element to be deleted is the last
element and we need to move through the whole list.

Auxiliary Space: O(1), As constant extra space is used.

Advantages of Circular Linked Lists:


 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.

 Useful for implementation of a queue. Unlike this implementation, we don’t need to
maintain two pointers for front and rear if we use a circular linked list. We can

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

maintain a pointer to the last inserted node and the front can always be obtained
as next of last.

 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 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.
 Circular Doubly Linked Lists are used for the implementation of advanced data
structures like the Fibonacci Heap.

Disadvantages of circular linked list:


 Compared to singly linked lists, circular lists are more complex.
 Reversing a circular list is more complicated than singly or doubly reversing a
circular list.
 It is possible for the code to go into an infinite loop if it is not handled carefully.
 It is harder to find the end of the list and control the loop.

Applications of circular linked lists:


 Multiplayer games use this to give each player a chance to play.
 A circular linked list can be used to organize multiple running applications on an
operating system. These applications are iterated over by the OS.
Why circular linked list?
 A node always points to another node, so NULL assignment is not necessary.
 Any node can be set as the starting point.
 Nodes are traversed quickly from the first to the last.

Menu-driven program in C implementing all operations


on circular singly linked list
1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. int data;
6. struct node *next;
7. };
8. struct node *head;
9.
10. void beginsert ();
11. void lastinsert ();

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

12. void randominsert();


13. void begin_delete();
14. void last_delete();
15. void random_delete();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 7)
22. {
23. printf("\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\n");
26. printf("\n1.Insert in begining\n2.Insert at last\n3.Delete from Beginning\n4.Delete
from last\n5.Search for an element\n6.Show\n7.Exit\n");
27. printf("\nEnter your choice?\n");
28. scanf("\n%d",&choice);
29. switch(choice)
30. {
31. case 1:
32. beginsert();
33. break;
34. case 2:
35. lastinsert();
36. break;
37. case 3:
38. begin_delete();
39. break;
40. case 4:
41. last_delete();
42. break;
43. case 5:
44. search();
45. break;
46. case 6:
47. display();

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

48. break;
49. case 7:
50. exit(0);
51. break;
52. default:
53. printf("Please enter valid choice..");
54. }
55. }
56. }
57. void beginsert()
58. {
59. struct node *ptr,*temp;
60. int item;
61. ptr = (struct node *)malloc(sizeof(struct node));
62. if(ptr == NULL)
63. {
64. printf("\nOVERFLOW");
65. }
66. else
67. {
68. printf("\nEnter the node data?");
69. scanf("%d",&item);
70. ptr -> data = item;
71. if(head == NULL)
72. {
73. head = ptr;
74. ptr -> next = head;
75. }
76. else
77. {
78. temp = head;
79. while(temp->next != head)
80. temp = temp->next;
81. ptr->next = head;
82. temp -> next = ptr;
83. head = ptr;
84. }

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

85. printf("\nnode inserted\n");


86. }
87.
88. }
89. void lastinsert()
90. {
91. struct node *ptr,*temp;
92. int item;
93. ptr = (struct node *)malloc(sizeof(struct node));
94. if(ptr == NULL)
95. {
96. printf("\nOVERFLOW\n");
97. }
98. else
99. {
100. printf("\nEnter Data?");
101. scanf("%d",&item);
102. ptr->data = item;
103. if(head == NULL)
104. {
105. head = ptr;
106. ptr -> next = head;
107. }
108. else
109. {
110. temp = head;
111. while(temp -> next != head)
112. {
113. temp = temp -> next;
114. }
115. temp -> next = ptr;
116. ptr -> next = head;
117. }
118.
119. printf("\nnode inserted\n");
120. }
121.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

122. }
123.
124. void begin_delete()
125. {
126. struct node *ptr;
127. if(head == NULL)
128. {
129. printf("\nUNDERFLOW");
130. }
131. else if(head->next == head)
132. {
133. head = NULL;
134. free(head);
135. printf("\nnode deleted\n");
136. }
137.
138. else
139. { ptr = head;
140. while(ptr -> next != head)
141. ptr = ptr -> next;
142. ptr->next = head->next;
143. free(head);
144. head = ptr->next;
145. printf("\nnode deleted\n");
146.
147. }
148. }
149. void last_delete()
150. {
151. struct node *ptr, *preptr;
152. if(head==NULL)
153. {
154. printf("\nUNDERFLOW");
155. }
156. else if (head ->next == head)
157. {
158. head = NULL;

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

159. free(head);
160. printf("\nnode deleted\n");
161.
162. }
163. else
164. {
165. ptr = head;
166. while(ptr ->next != head)
167. {
168. preptr=ptr;
169. ptr = ptr->next;
170. }
171. preptr->next = ptr -> next;
172. free(ptr);
173. printf("\nnode deleted\n");
174.
175. }
176. }
177.
178. void search()
179. {
180. struct node *ptr;
181. int item,i=0,flag=1;
182. ptr = head;
183. if(ptr == NULL)
184. {
185. printf("\nEmpty List\n");
186. }
187. else
188. {
189. printf("\nEnter item which you want to search?\n");
190. scanf("%d",&item);
191. if(head ->data == item)
192. {
193. printf("item found at location %d",i+1);
194. flag=0;
195. }

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

196. else
197. {
198. while (ptr->next != head)
199. {
200. if(ptr->data == item)
201. {
202. printf("item found at location %d ",i+1);
203. flag=0;
204. break;
205. }
206. else
207. {
208. flag=1;
209. }
210. i++;
211. ptr = ptr -> next;
212. }
213. }
214. if(flag != 0)
215. {
216. printf("Item not found\n");
217. }
218. }
219.
220. }
221.
222. void display()
223. {
224. struct node *ptr;
225. ptr=head;
226. if(head == NULL)
227. {
228. printf("\nnothing to print");
229. }
230. else
231. {
232. printf("\n printing values ... \n");

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

233.
234. while(ptr -> next != head)
235. {
236.
237. printf("%d\n", ptr -> data);
238. ptr = ptr -> next;
239. }
240. printf("%d\n", ptr -> data);
241. }
242.
243. }

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Que 1.23. Write an algorithm to insert a node at the end in a circular linked list.

AKTU 2017-18, Marks 07

Ans:

C Function
1. void lastinsert(struct node*ptr, struct node *temp, int item)
2. {
3. ptr = (struct node *)malloc(sizeof(struct node));
4. if(ptr == NULL)
5. {
6. printf("\nOVERFLOW\n");
7. }
8. else
9. {
10. ptr->data = item;
11. if(head == NULL)
12. {
13. head = ptr;
14. ptr -> next = head;
15. }
16. else
17. {
18. temp = head;

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

19. while(temp -> next != head)


20. {
21. temp = temp -> next;
22. }
23. temp -> next = ptr;
24. ptr -> next = head;
25. }
26. }
27.
28. }

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

1.24-Write advantages and disadvantages of linked list over arrays.

Ans:

Advantages Of Linked List:


 Dynamic data structure: A linked list is a dynamic arrangement so it can grow
and shrink at runtime by allocating and deallocating memory. So there is no need
to give the initial size of the linked list.
 No memory wastage: In the Linked list, efficient memory utilization can be
achieved since the size of the linked list increase or decrease at run time so there is
no memory wastage and there is no need to pre-allocate the memory.
 Implementation: Linear data structures like stacks and queues are often easily
implemented using a linked list.
 Insertion and Deletion Operations: Insertion and deletion operations are quite
easier in the linked list. There is no need to shift elements after the insertion or
deletion of an element only the address present in the next pointer needs to be
updated.
 Flexible: This is because the elements in Linked List are not stored in contiguous
memory locations unlike the array.
 Efficient for large data: When working with large datasets linked lists play a
crucial role as it can grow and shrink dynamically.
 Scalability: Contains the ability to add or remove elements at any position.
Disadvantages Of Linked List:
 Memory usage: More memory is required in the linked list as compared to an
array. Because in a linked list, a pointer is also required to store the address of the
next element and it requires extra memory for itself.
 Traversal: In a Linked list traversal is more time-consuming as compared to an
array. Direct access to an element is not possible in a linked list as in an array by
index. For example, for accessing a node at position n, one has to traverse all the
nodes before it.
 Reverse Traversing: In a singly linked list reverse traversing is not possible, but
in the case of a doubly-linked list, it can be possible as it contains a pointer to the
previously connected nodes with each node. For performing this extra memory is
required for the back pointer hence, there is a wastage of memory.
 Random Access: Random access is not possible in a linked list due to its dynamic
memory allocation.
 Lower efficiency at times: For certain operations, such as searching for an
element or iterating through the list, can be slower in a linked list.
 Complex implementation: The linked list implementation is more complex when
compared to array. It requires a complex programming understanding.
 Difficult to share data: This is because it is not possible to directly access the
memory address of an element in a linked list.
 Not suited for small dataset: Cannot provide any significant benefits on small
dataset compare to that of an array.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

1.25-Discuss the representation of polynomial of single variable using linked list.


Write 'C' functions to add two such polynomials represented by linked list.

Ans:

Each node of a linked list representing polynomial constitute three parts:

o The first part contains the value of the coefficient of the term.
o The second part contains the value of the exponent.
o The third part, LINK points to the next term (next node).

The structure of a node of a linked list that represents a polynomial is shown below:

Example:
Input:
1st number = 5x2 + 4x1 + 2x0
2nd number = -5x1 - 5x0
Output:
5x2-1x1-3x0
Input:
1st number = 5x3 + 4x2 + 2x0
2nd number = 5x^1 - 5x^0
Output:
5x3 + 4x2 + 5x1 - 3x0

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

Polynomial Addition

Implementation:

// C++ program for addition of two polynomials

// using Linked Lists

#include <bits/stdc++.h>

using namespace std;

// Node structure containing power and coefficient of

// variable

struct Node {

int coeff;

int pow;

struct Node* next;

};

// Function to create new node

void create_node(int x, int y, struct Node** temp)

struct Node *r, *z;

z = *temp;

if (z == NULL) {

r = (struct Node*)malloc(sizeof(struct Node));

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

r->coeff = x;

r->pow = y;

*temp = r;

r->next = (struct Node*)malloc(sizeof(struct Node));

r = r->next;

r->next = NULL;

else {

r->coeff = x;

r->pow = y;

r->next = (struct Node*)malloc(sizeof(struct Node));

r = r->next;

r->next = NULL;

// Function Adding two polynomial numbers

void polyadd(struct Node* poly1, struct Node* poly2,

struct Node* poly)

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

while (poly1->next && poly2->next) {

// If power of 1st polynomial is greater then 2nd,

// then store 1st as it is and move its pointer

if (poly1->pow > poly2->pow) {

poly->pow = poly1->pow;

poly->coeff = poly1->coeff;

poly1 = poly1->next;

// If power of 2nd polynomial is greater then 1st,

// then store 2nd as it is and move its pointer

else if (poly1->pow < poly2->pow) {

poly->pow = poly2->pow;

poly->coeff = poly2->coeff;

poly2 = poly2->next;

// If power of both polynomial numbers is same then

// add their coefficients

else {

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

poly->pow = poly1->pow;

poly->coeff = poly1->coeff + poly2->coeff;

poly1 = poly1->next;

poly2 = poly2->next;

// Dynamically create new node

poly->next

= (struct Node*)malloc(sizeof(struct Node));

poly = poly->next;

poly->next = NULL;

while (poly1->next || poly2->next) {

if (poly1->next) {

poly->pow = poly1->pow;

poly->coeff = poly1->coeff;

poly1 = poly1->next;

if (poly2->next) {

poly->pow = poly2->pow;

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

poly->coeff = poly2->coeff;

poly2 = poly2->next;

poly->next

= (struct Node*)malloc(sizeof(struct Node));

poly = poly->next;

poly->next = NULL;

// Display Linked list

void show(struct Node* node)

while (node->next != NULL) {

printf("%dx^%d", node->coeff, node->pow);

node = node->next;

if (node->coeff >= 0) {

if (node->next != NULL)

printf("+");

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

// Driver code

int main()

struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;

// Create first list of 5x^2 + 4x^1 + 2x^0

create_node(5, 2, &poly1);

create_node(4, 1, &poly1);

create_node(2, 0, &poly1);

// Create second list of -5x^1 - 5x^0

create_node(-5, 1, &poly2);

create_node(-5, 0, &poly2);

printf("1st Number: ");

show(poly1);

Downloaded by pooja Goel (poojagoel2441994@gmail.com)


lOMoARcPSD|17918814

printf("\n2nd Number: ");

show(poly2);

poly = (struct Node*)malloc(sizeof(struct Node));

// Function add two polynomial numbers

polyadd(poly1, poly2, poly);

// Display resultant List

printf("\nAdded polynomial: ");

show(poly);

return 0;

Output
1st Number: 5x^2+4x^1+2x^0
2nd Number: -5x^1-5x^0
Added polynomial: 5x^2-1x^1-3x^0

Time Complexity: O(m + n) where m and n are number of nodes in first and second
lists respectively.

Space Complexity: O(m+n), since we create a new linked list of size m + n to store
the result of the addition of the two polynomials.

Downloaded by pooja Goel (poojagoel2441994@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy