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

DATA STRUCTURE Using C

(KCS-301)

Sanjeev Kr. Kapoor


(Assistant Professor, IT Department, KIET, Ghaziabad)
What is data?

19-Sep-22 2
What is Information?

19-Sep-22 3
• What is structure??
Can we extract information without structure

19-Sep-22 5
As Its Data structure using C
• Do you know C programming..?

Pre-requisite:
• Control statements
• Loops
• Functions and recursion
• Arrays
• Strings
• Structures
• Pointers
What is Data Structure?
• Data structure is study for knowing the right way of storing data in
digital space.
• Data structures imparts discipline among the data for efficient and
fast access.

• Way of storing and organizing set of related data in computer


memory so that data can be accessed and manipulated efficiently
and easily.
• The Logical or Mathematical model of a particular organization of
data.

7
Definition..
• Data structure is representation of the logical relationship
existing between individual elements of data.
• In other words, a data structure is a way of organizing all data
items that considers not only the elements stored but also their
relationship to each other.
• Data structures defines a particular way of storing and
organizing data in a computer so that it can be used
efficiently.
Importance of data structure
• DS is core foundation of writing good codes, reduces coding cost, and
enhances data accuracy being ultimate goal of any company.
• Major IT Companies/High Paying companies like google, Amazon,
Microsoft often ask questions related to data structures to check the
problem solving capability of candidate.
• Learning data structures leads to gradual improvement in problem
solving skills.
• Competent students in data structures and algorithm are also good in
data processing, reasoning and aptitude problems, thus directly
increases chances of placement.
Unit-1 Syllabus
Course outcomes( Data Structures- KCS301)
CO CO Statement BT Knowledge level

CO 1 Apply the knowledge of various data structures and its operations Apply Conceptual,
Procedural

CO 2 Apply standard algorithms for searching and sorting Apply Conceptual,


Procedural

CO 3 Analyze efficiency of different algorithms using time and space complexity Analyze Conceptual,
Procedural

CO 4 Explore the concept, application and implementation of recursion Analyze Conceptual,


Procedural

CO 5 Implement the suitable data structure with respect to its performance to Create Conceptual,
model a real world problem Procedural,
Metacognitive
What is a Computer Program?
• To exactly know, what is data structure? We must know:
• What is a computer program?

Some mysterious
processing Output
Input

12
Problem??
• You Need to find your unique name from a sorted names list in word
file of 50000 pages manually. What approach you will use???
Introduction

• Data structure affects the design of both structural &


functional aspects of a program.
Program=algorithm + Data Structure
• Where an algorithm is a step by step procedure to
solve a particular problem.
Introduction..
• That means, algorithm is a set of instruction written
to carry out certain tasks & the data structure is the
way of organizing the data with their logical
relationship retained.
• To develop a program of an algorithm, we should
select an appropriate data structure for that
algorithm.
• Therefore algorithm and its associated data
structures form a program.
Data structure example?

array

Linked list

queue
tree stack

16
Real life applications areas
• 2- D array for record keeping
• Stack of plates
• Queue for buses/other transport
• Printer queue
• Google maps

19-Sep-22 17
Classification of Data Structure
• Data structure are normally divided into two broad categories:
• Primitive Data Structure
• Non-Primitive Data Structure
Classification of Data Structure

Data structure

Primitive DS Non-Primitive DS

Integer Float Character Pointer


Classification of Data Structure

Non-Primitive DS

Linear Non-Linear

Array Queue Graph Trees

Link List Stack


Primitive Data Structure
• There are basic structures and directly operated upon by the machine
instructions.
• In general, there are different representation on different computers.
• Integer, Floating-point number, Character constants, string constants,
pointers etc, fall in this category.
Non-Primitive Data Structure
• There are more sophisticated data structures.
• These are derived from the primitive data structures.
• The non-primitive data structures emphasize on structuring of a group
of homogeneous (same type) or heterogeneous (different type) data
items.
Non-Primitive Data Structure
• Lists, Stack, Queue, Tree, Graph are example of non-primitive data
structures.
• The design of an efficient data structure must consider operations to be
performed on the data structure.
More applications of data structures
• Compiler design( Hash tables in identifier lookup)

• Operating system (Linked list: Memory allocation, Trees(File system))

• DBMS (Graphs, trees, arrays)

• AI (e.g. arrays)
Performance analysis of
Algorithm
Algorithm?
• Refers to a method that used by computer for solution of a problem.
• It is finite set of instructions that, if followed accomplish a certain task.
Properties of algorithm:
• Input: Zero or more quantities (externally produced)
• Output: One or more quantities
• Definiteness: Clarity, precision of each instruction
• Finiteness: The algorithm has to stop after a finite (may be very
large) number of steps
• Effectiveness: Each instruction has to be basic enough and feasible
Complexity Analysis of Algorithms
(Time and space complexity)
• Devising  Validating  Analyzing
• As an algorithms is executed, It uses CPU for operations and Memory for holding data
and program.

• So Analysis of Algorithms here refer to task of determining how much computing time
and storage an algorithm requires.

• Based on such analysis we judge the algorithm quality.

• Such analysis of algorithm is complexity analysis.

• Estimates regarding space required is Space complexity and estimates regarding time is
called time complexity.
Why complexity analysis Required?
Space Complexity

• Instruction Space
• Data space

Instance of each function call is placed in stack. Along with local


argument and Return address.

All this contribute the Extra memory and we need to minimize this
through better programming style.
Why Time Complexity
• Often more important than space complexity
• space available (for computer programs!) tends to be larger and larger
• time is still a problem for all of us

• 3 to 4 GHz processors on the market


• still …
• researchers estimate that the computation of various transformations for 1 single DNA chain
for one single protein on 1 TerraHZ computer would take about 1 year to run to completion
• So Algorithms running time is an important issue.
Worst-case, Average-case, Best-case Time Complexity
• Worst-case running time This denotes the behavior of an algorithm
with respect to the worst possible case of the input instance.

• The worst-case running time of an algorithm is an upper bound on the


running time for any input.

• Therefore, having the knowledge of worst-case running time gives us


an assurance that the algorithm will never go beyond this time limit.
Worst-case, Average-case, Best-case Time Complexity
• Average-case running time
The average-case running time of an algorithm is an estimate of the
running time for an ‘average’ input.

• It specifies the expected behavior of the algorithm when the input is


randomly drawn from a given distribution.

• Average-case running time assumes that all inputs of a given size are
equally likely.
Worst-case, Average-case, Best-case Time Complexity
• Best-case running time The term ‘best-case performance’ is used to
analyze an algorithm under optimal conditions.

• For example, the best case for a simple linear search on an array
occurs when the desired element is the first in the list.

• However, while developing and choosing an algorithm to solve a


problem, we hardly base our decision on the best-case performance.

• It is always recommended to improve the average performance and


the worst-case performance of an algorithm.
Estimating running time(Experimental approach)
• Write a program to implement 9000
the algorithm. 8000

7000
• Run the program with inputs of
6000
varying size and composition.

Time (ms)
5000

• Get an accurate measure of the 4000


actual running time (e.g. system 3000
call date).
2000

1000
• Plot the results.
0
• Problems?
0 50 100
Input Size
Limitations of Experimental approach

• The algorithm has to be implemented, which may take


a long time and could be very difficult.

• Results may not be indicative for the running time on


other inputs that are not included in the experiments.

• In order to compare two algorithms, the same


hardware and software must be used.
Use a Theoretical Approach
• Based on high-level description of the algorithms, rather than
language dependent implementations
• Makes possible an evaluation of the algorithms that is independent
of the hardware and software environments
• Count the instructions and frequency of instructions in program
based on input.
Expressing Time Complexity
• The time and space complexity can be expressed using a function f(n)
where n is the input size for a given instance of the problem being
solved.
• Expressing the complexity is required when
• We want to predict the rate of growth of complexity as the input size of the problem
increases.
• There are multiple algorithms that find a solution to a given problem and we need to
find the algorithm that is most efficient.
• The most widely used notation to express this function f(n) is the Big
O notation. It provides the upper bound for the complexity.
Algorithm Efficiency
• If a function is linear (without any loops or recursions), the efficiency
of that algorithm or the running time of that algorithm can be given
as the number of instructions it contains.
• However, if an algorithm contains loops, then the efficiency of that
algorithm may vary depending on the number of loops and the
running time of each loop in the algorithm.
Algorithm Efficiency
• Linear Loops
To calculate the efficiency of an algorithm that has a single loop, we
need to first determine the number of times the statements in the
loop will be executed.

Efficiency is directly proportional to the number of iterations. Hence,


the general formula in the case of linear loops may be given as
f(n) = O(n)
Algorithm Efficiency
Consider the loop given below:

Here, the number of iterations is half the number of the loop factor.
So, here the efficiency can be given as
Algorithm Efficiency
• Logarithmic Loops
In logarithmic loops, the loop-controlling variable is either multiplied or divided
during each iteration of the loop. For example, look at the loops given below:

• Both loops will be executed only 10 times and not 1000 times

• we can conclude that the efficiency of loops in which iterations divide or multiply
the loop-controlling variables can be given as
Algorithm Efficiency
• Nested Loops
Linear logarithmic loop

The efficiency of such loops can be given as f(n) = n log n.


• Quadratic loop
printf(“Hellowordl”)  C1 ignoring contants O(1)
--------------------------------------------
n=10C1
for(i=0;i<n;i++)C2
print(“Helloworld”) n*C3 Total: C1+C2+n*C3 ignoring Constant O(n)
--------------------------------------------------------------------------------
for(i=0;i<n;i++)C1
printf(“Helloworld”) n*C2
for(j=0;j<n;j++)C3
printf(“Data structures”) n*C4

Total: C1+n*C2+C3+n*C4C1+C3+(C2+C4)n ignoring Constant O(n)


for(i=0;i<n;i++)C1
{ for(j=0;j<n;j++)n*C2
printf(“Data structures”)  n*n*C3

Total: C1+n*C2+n2C3 ignoring Constant and lower powers


O(n2)
Some Numbers
2 3 n
log n n n log n n n 2
0 1 0 1 1 2
1 2 2 4 8 4
2 4 8 16 64 16
3 8 24 64 512 256
4 16 64 256 4096 65536
5 32 160 1024 32768 4294967296
Growth Rate of Running Time
• Changing computer hardware / software
• Affects T(n) by a constant factor
• Does not alter the growth rate of T(n)
• With this background the time complexity may
expressed in terms of special notations called
asymptotic notations.
Try to find the running time of program
fragment
Q1.
for(i=n;i>=1;i=i/2)
{ print(“Computed running time”)}
Q2.
for(i=2;i<=n;i=i2)
{ print(“Computed running time”)}
• Q1. logn , n/2k<1 or n/2k=1 n=2k taking log on both sides
• Klog2=logn k=log n
Step of 1 2 3 4 .. K K+1
loop
i n n/2 n/2*2 n/2*2*2 n/2k-1 n/2k
Q2. log log n
Similarly we can verify for Q2. 2 2 k>n, 2k log2=logn k=log log n

Step of 1 2 3 4 .. K K+1
loop
i 2 Pow(2,p Pow(2,p Pow(2,p Pow(2,p Pow(2,p
ow(2,1) ow(2,2) ow(2,3) ow(2,k- ow(2,k)
1)
Estimate the time complexity
Solution
Asymptotic Notations
• Using asymptotic notations, we analyze the complexities of an
algorithm and its performance.

• Using the asymptotic notations, we determine and show the


complexities after analyzing it.
• Therefore, there are three types of asymptotic notations through which
we can analyze the complexities of the algorithms.
• Big O Notation (O):
• Omega Notation (Ω):
• Theta Notation (Θ)
O-notation
For function g(n), we define O(g(n)),
big-O of n, as the set:
F(n)=O(g(n)) :
 positive constants c and n0, such
that n  n0,
we have 0  f(n)  cg(n) }
Intuitively: Set of all functions whose rate of
growth is the same as or lower than that of
g(n).

g(n) is an asymptotic upper bound for f(n).


f(n) = O(g(n)).

Comp 122
Examples
O(g(n)) = {f(n) :  positive constants c and n0, such
that n  n0, we have 0  f(n)  cg(n) }

• Any linear function n + 5 is in O(n2). How?


• Show that 3n3=O(n4) for appropriate c and n0.

Comp 122
Omega Notation, Ω:
• Omega Notation (Ω): It represents the lower bound of the runtime of an
algorithm. It is used for calculating the best time an algorithm can take to
complete its execution, i.e., it is used for measuring the best case
time complexity of an algorithm.

• For example, for a function f(n)


Ω(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ c
g(n) ≤ f(n), for all n ≥ n0}
Omega Notation, Ω:
Let's consider a simple example.
If f(n) = 2n+3, g(n) = n,
Is f(n)= Ω (g(n))?
It must satisfy the condition:
f(n)>=c.g(n)
To check the above condition, we first replace f(n) by 2n+3 and g(n) by
n.
2n+3>=c*n
Suppose c=1
2n+3>=n (This equation will be true for any value of n starting from 1).
Therefore, it is proved that g(n) is big omega of 2n+3 function.
Theta Notation, θ
• Theta Notation (Θ(n)): It carries the middle characteristics of both Big O and
Omega notations as it represents the lower and upper bound of an algorithm.

• For example, for a function f(n)


Θ(g(n)) = {f(n) : There exist positive constant c1, c2 and n0 such that 0
≤ c1 g(n) ≤ f(n) ≤ c2 g(n), for all n ≥ n0}
Theta Notation, θ
Let's consider the same example where
f(n)=2n+3 and g(n)=n
As c1.g(n) should be less than f(n) so c1 has to be 1 whereas c2.g(n) should be greater than f(n) so c2 is
equal to 5. The c1.g(n) is the lower limit of the of the f(n) while c2.g(n) is the upper limit of the f(n).
c1.g(n)<=f(n)<=c2.g(n)
Replace g(n) by n and f(n) by 2n+3
c1.n <=2n+3<=c2.n
if c1=1, c2=5, n=1
1*1 <=2*1+3 <=5*1
1 <= 5 <= 5 // for n=1, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
If n=2
1*2<=2*2+3<=5*2
2<=7<=10 // for n=2, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
Therefore, we can say that for any value of n, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n). Hence, it is
proved that f(n) is big theta of g(n). So, this is the average-case scenario which provides the realistic time
complexity.
Relations Between Q, O, W

Comp 122
Example

• Derive the big O notation, if f(n) =8n+7 and g(n)=n


To show f(n) is O(g(n)), we must consider positive constant C and
integer n0 such that f(n)<=cg(n) for all n>n0
or 8n+7<=Cn / 8n+7=8n+7n simple method so we find C
Let C=15
8n+7<=15n
7<=7n
1<=n
Big-O Examples
2n2 + 5 n+1 = O(n2)

2n2 + 5 n+1 = O(n3)

CSE 326 Autumn 2001


Asymptotic Analysis
66
Big-O Examples.. solution
2n2 + 5 n+1 = O(n2)
follows from … ( 2n2 + 5 n+1 )  4 n2 for n  1, C=8

2n2 + 5 n+1 = O(n3)


follows from …( 2n2 + 5n+1 )  4 n3 for n  1, C=8

Alternat answers are also possible. (can we take n=4, c=1 in


second case)

CSE 326 Autumn 2001


Asymptotic Analysis
67
Big-O Common Names
constant: O(1)
logarithmic: O(log n)
linear: O(n)
log-linear: O(n log n)
superlinear: O(n1+c) (c is a constant > 0)
quadratic: O(n2)
polynomial: O(nk) (k is a constant)
exponential: O(cn) (c is a constant > 1)

CSE 326 Autumn 2001


Asymptotic Analysis
68
• Prove that running time T(n) = n3 + 20n + 1 is O(n3)
• Prove that running time T(n) = n3 + 20n + 1 is not O(n2)
• Prove that running time T(n) = n3 + 20n + 1 is O(n4 )
Solution -1
Solution-2
Solution-3
O(1)
O(n)
O(n2)
This is O(2n), which we just call O(n).
Drop the less significant terms
Here our runtime is O(n + n2), which we just call O(n2).

O(n3 + 50n2 + 10000) is O(n3)


O((n + 30) * (n + 5)) is O(n2)
Topic of Discussion:

Space Time Tradeoff


Time Space Tradeoff
In algorithm Design: It is an phenomenon where
Where if try to decrease the space complexity of program. It may
lead to increase in time complexity of the program.
Similarly if design of algorithm is changed to reduce the time
complexity its space complexity may increase.
Space & time requirement may be compromised to some extent but
not to infinite.

Most computers have a large amount of space, but not infinite


space. Also, most people are willing to wait a little while for a
big calculation, but not forever
Time Space Trade-off example
• Suppose two algorithm exist for same problem.
• Scenario-1
Algorithm Time (Seconds) Space(Bytes)
Approach -1 10 100
Approach-2 12 110
Approach-1 seems better

• Scenario-2
Algorithm Time (seconds) Space(Bytes)
Approach -1 10 100
Approach-2 8 200
Hard to decide, Matter of choice at cost of others
Example..:
• If data is stored uncompressed, it takes more space but less time than
if the data were stored compressed but it takes time to run the
compression algorithm
• Loop based and non loop based programs
• Recursive vs. Non Recursive programs.
Recursive vs. Non Recursive Program
(An Example of space time tradeoff)

• Factorial with Recursion


Factorial without Recursion
int fact(int n)
int fact(int n)
{ if(n<=1) return 1
{f=1
else return n*fact(n-1)
for(i=2;i<=n;i++)
}
{f=f*i }
#less lines of code
return f
#Less memory for variables//although
}
Machine dependent.
#More Lines of code/Statements
# But more time required
#More memory required.
# Constant stack space depending on
#Less time required to execute. value of n.
Compressed vs. Non Compressed data
(An Example of space time tradeoff)

• Data=AAAABBBBBBCCCCC • Data=AAAABBBBBBCCCCC
• Apply Compression Algo. • Use Uncompressed data
• Compressed data: A4B6C5 directly But will take more
Space.
To Access:
• Apply Decompression algo
on Data to get
AAAABBBBBBCCCCC from
A4B6C5
• Then Use.
ADTs: The Entities which carries blueprint of definitions of data attributes and associated operations
while user is not aware of Implementation
• Abstract Data type (ADT) is a type (or
class) for objects whose behavior is
defined by a set of value and a set of • It does not specify how data will be
operations. organized in memory and what
algorithms will be used for
• The definition of ADT only mentions implementing the operations.
what operations are to be performed
but not how these operations will be • It is called “abstract” because it gives
implemented an implementation-independent
view.
• The user of data type does not need
to know how that data type is
implemented
• E.g. we have been using Primitive
values like int, float, char
ADT as a black box which hides the inner structure and design of the data type from
User/Application

SK Classes …. (Sanjeev
Kr. Kapoor, AP, KIET Group of Institutions)
Array ADT
• Instances: ordered collection of zero or more elements.
• Operations. :
• 1. Is emplty
• 2. size
• 3. Index
• 4. Insert
• 5. delete
• 6. Traverse
Stack as ADT: Conceptual View(LIFO)
Stack as an ADT:
• e.g. Stack if we consider as ADT. We need to
understand what operations it needs to
perform:
1. Push(): To insert the element in stack list
2. Pop(): To delete the element from stack list
3. Create(): To create a stack
4. Isempty: To check whether stack empty or
not
5. Size(): to Know size of stack

SK Classes …. (Sanjeev
Kr. Kapoor, AP, KIET Group of Institutions)
Others examples of ADTs
• List
• Queue
• Graph
• Tree etc.
Summary Quiz
• What is data structure
• Example of Non Linear data structure
• Why we need data structure?
• Explain static and dynamic Implementation?

19-Sep-22 91
Try the following
• Write a program/Algorithm for Largest of three numbers.

• State the output of


Void main()
{int i;
for(i=0;i<10;i++);
printf(“%d”, i)
if (i==5)
break;
}

Void main()
{int i;
for(i=0;i<10;i++)
printf(“%d”, i)
break;
}

19-Sep-22 92
Arrays
 An array is a list of a finite number of homogenous
(similar data) elements.
 This means that an array can store either all integers, all
floating point numbers, all characters (string) or any other
complex data type but all of same type.
Array elements are stored in consecutive memory location
called index or subscript.
Basics of Array
• An array is a type of data structure that stores a fixed-size of a homogeneous
collection of data. In short, we can say that array is a collection of variables of the
same type.
• For example, if you want to store 100 integers, you can create a 1D array for it.
int data[100];
• Declaration of a 1-dimentional array
dataType arrayName[arraySize];
Example: float mark[5];
• Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning,
it can hold 5 floating-point values.
• It's important to note that the size and type of an array cannot be changed once it is
declared.

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Example of Array

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Dimensions of an Array
• A one-dimensional array is like a list.
float marks[5];
• A two dimensional array is like a table.
int x[3][3];
• The C language places no limits on the number of
dimensions in an array, though specific
implementations may.
int a[2][3][4];

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Initializing Arrays
• Arrays may be initialized when they are declared, just as any other variables.
• Place the initialization data in curly {} braces following the equals sign.
int i_Array[6] = { 1, 2, 3, 4, 5, 6 };
• An array may be partially initialized, by providing fewer data items than the
size of the array. The remaining array elements will be automatically
initialized to zero.
float f_Array[ 10 ] = { 1.0, 5.0, 20.0 };
• If an array is to be completely initialized, the dimension of the array is not
required. The compiler will automatically size the array to fit the initialized
data.
int data[ ] = { 34,34,78,23,45,89};

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Using Arrays
• Elements of an array are accessed by specifying the index (offset ) of the desired element
within square [ ] brackets after the array name. Array subscripts must be of integer type.
• Array name always reflects the base address of an array.
• Array indices start at zero in C, and go to one less than the size of the array. For example, a
five element array will have indices zero through four.
• The index in C is actually an offset from the beginning of the array. (The first element is at
the beginning of the array, and hence has zero offset.)

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
OPERATIONS ON ARRAYS
• There are a number of operations that can be preformed on arrays. These operations
include:
• Traversing an array
• Inserting an element in an array
• Searching an element in an array
• Deleting an element from an array
• Merging two arrays
• Sorting an array in ascending or descending order

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Algo. For Traversing in linear array
• LA is a linear array with UB upper bound
and LB lower bound for traversing
we apply PROCESS to each element of LA
Steps are:
1.Set k=LB
2.Repeat step 3 and 4 while k<=UB
3.Apply PROCESS to LA [k]
4.k=k+1
5.exit
Inserting an element in array
• INSERT (LA, N, k, ITEM)
Here LA is a Linear array with N
elements and K is a positive integer.
This algorithm inserts an element
ITEM into the Kth position in LA.
Steps are:
1.Set j=N
2. Repeats step 3 and 4 while j>=k
3.Set LA[j+1]=LA[j]
4.Set j=j-1
5.Set LA[k]=ITEM
6.Set N=N+1
7.Exit
Delete an element in array
• DELETE (LA, N, k, ITEM)
Here LA is a Linear array with N elements and K is a positive integer.
This algorithm deletes the Kth element from LA.
Steps are:
1.Set ITEM = LA[k]
2. Repeat for j = k to N-1
Set LA[j] = LA[j+1]
3.Set N=N-1
4.Exit
CALCULATING THE ADDRESS OF 1D ARRAY ELEMENTS
• Remember that the array name is a symbolic reference to the address of the first byte of
the array.
• The subscript or the index represents the offset from the beginning of the array to the
element being referenced. That is, with just the array name and the index, C can calculate
the address of any element in the array.
• The address of other data elements can simply be calculated using the base address of the
array.
• The formula to perform this calculation is, Address of data element,
Address of Element A[i] = Base Add. of Array A + w (i – lower_bound)
Here, A is the array, i is the index of the element of which we have to calculate the address
and w is the size of one element in memory, for example, size of int is 2.

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
CALCULATING THE ADDRESS OF 1D ARRAY ELEMENTS

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
TWO-DIMENSIONAL ARRAYS
• One-dimensional arrays are organized linearly in only one direction. But at times,
we need to store data in the form of grids or tables.
• A two-dimensional array is specified using two subscripts where the first subscript
denotes the row and the second denotes the column.
• The C compiler treats a two-dimensional array as an array of one-dimensional
arrays.
• Consider the following 2D array declaration:
int marks[3][5];
The pictorial form of a two-dimensional array is

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
2D Arrays
Initialization of 2D Array in C
• In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously.
• However, this will not work with 2D arrays. We will have to define at least the
second dimension of the array.
• The two-dimensional array can be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Or
int arr[ ][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

But not int arr[4][ ]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};


Or int arr[ ][ ]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
DATA STRUCTURE (KCS-301)
(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
STORING A TWO-DIMENSIONAL ARRAY
• Although we have shown a rectangular picture of a two-
dimensional array, in the memory, these elements actually will be
stored sequentially.
• There are two ways of storing a two dimensional array in the
memory.
• Row major order
• Column major order
• Row Major Order
The elements of the array are stored row by row where n elements
of the first row will occupy the first n locations.
• For example, Elements of a 3 × 4 2D array in row major order

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
STORING A TWO-DIMENSIONAL ARRAY
• Column Major Order
• When we store the elements in a column major order, the elements of the first
column are stored before the elements of the second and third column.
• That is, the elements of the array are stored column by column where m elements
of the first column will occupy the first m locations.
• For example, Elements of a 4 × 3 2D array in column major order

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Address Calculation terminology (General)
• Elements of an array A may be denoted by the subscript
notation
A1, A2, …………… An
Or
A[1], A[2],………..A[n]
• The number n of elements is called the length or size of
the array.
• The number n in A[n] is called a subscript / index and A[n]
is called a subscript variable.

In C array is declared as
int a[10], here index starts from 0 (LB).
Size of array is fixed. Being static allocation.
• Length / Size of array = UB – LB + 1
• Where UB is the largest index, called the upper
bound, and LB is the smallest index, called the lower
bound of the array and
Length = UB if LB =1.

e.g. in c array LB=0, int a[10], LB=0, UB=9


so length= UB-LB+1=9-0+1=10
Example
• An automobile company uses an array AUTO to record the number of
automobiles sold each year from 1932 through 1984. Rather than
beginning the index set with 1, it is more useful to begin the index set
with 1932 so that
• AUTO[K] = number of automobiles sold in the year K.

Find the length of array AUTO.


Answer
• LB = 1932 is the lower bound and UB= 1984 is the upper bound of
AUTO.
• Length = UB – LB +1
• Length = 1984 – 1932 + 1 = 53
• That is, AUTO contains 53 elements and its index set consists of all
integers from 1932 through 1984
• Example :
• Int num[5]
• The array will store five integer values, its name is
num also called base address in C.
• num[0]=22, num[1] = 1, num[2]=30, num[3]=9,
num[4]=3
num

022 11 2 30 3 9 4 3
• The size of array can be determined as :
• Size = UB – LB +1
• For array num size will be :
• UB = 4
• LB = 0
• Size = 4 – 0 +1 = 5
• Size of array in bytes (i.e. amount of memory array occupies)
• Size in bytes = size of array x size of base type
• E.g. if we have array
int num [5];
• Then size in bytes = 5 x 2 = 10 bytes
• Similarly, if we have array
float num[5];
• Then size in bytes = 5 x 4 = 20 bytes
Addressing of element in 1-D Array in Memory map.
• Let A be a linear array stored in successive memory cells.
LOC(A[K]) = address of the element A[K] of the array A

1000
1001
1002
1003

• To calculate the address of any element of A formula is::


LOC(A[K])= Base (A) + w (K-lower bound)
• Base (A) =Address of the first element of A
• w =number of words per memory cell for the array
• K =any index of A
Example
• Consider the array AUTO, which records the number
of automobiles sold each year from 1932 through
1984. Suppose AUTO appears in memory as pictured.
That is Base(AUTO) = 200 and w = 4 words per
memory cell for AUTO Then
• LOC(AUTO[1932]) = 200,
• LOC(AUTO[1933])=204,
• LOC(AUTO[1934])=208,…..
• The address of the array element for the year K=1965
can be obtained by using formula.
Answer
• LOC(AUTO[1965]) = Base(AUTO) + w (1965 – lower bound)
• LOC(AUTO[1965])= 200 + 4 (1965 – 1932)
• LOC(AUTO[1965]) = 332
If base address is 400, w=2 bytes, find the address
of 4th element array with starting index 0.

• 406
Consider array a[-25,-24……+75+, base
address=1000,size of each element,w=10, find the
address of element at index 60
Consider array a[-25,-24……+75+, base
address=1000,size of each element,w=10, find the
address of element at index 60
• Solution

• Address(A[60])=1000+(60-(-25))*10
• 1000+85*10
• 1850
Two-Dimensional Array(General Terminology)
• A two dimensional array A is a collection of m * n elements
and each element is specified by pair of integers (such as J, K)
called subscripts
LB<=J<= UB AND
LB<=K<=UB
• Element of A with first subscript j and second subscript k will
denoted by
AJ,K or A[J,K]
• Two-dimensional arrays are called matrices in mathematics and
tables in business applications.
• The element A[J,K] appears in row J and column K
• A row is a horizontal list of elements and a column is a vertical
list of elements.
• Suppose A is a two-dimensional m x n array. The first
dimension of A contains the index set 1,2…..m with
lower bound 1 and upper bound m
• The second dimension of A contains the index set
1,2…..n with lower bound 1 and upper bound n.
• The length of a given dimension
Length = upper bound – lower bound + 1
• Size of array = m x n
EXAMPLE

• Let A be a 2D array such that


• A(2:5,-3:1)
• Here index set of dimensions 2,3,4,5 and -3,-2,-1,0,1
• Length of first dimension is 5-2+1=4
• Length of second dimension is 1-(-3)+1=5
• Size of A=4*5=20
Address calculation in 2D array: A[LBr…UBr, LBc…UBc]
• Let a 2D array A of m*n size, to compute the LOC (A[j,k]) using
the formula

LOC (A[j,k])=Base(A)+w[(N(j-LBr)+(k-LBc)]
(row major order)
Where Base(A) = address of 1st element of A, w = Bytes per
Element and N = total no. of columns in array=UBc-LBc+1/ UB2-
LB2+1

LOC (A[j,k])=Base(A)+w[(M(k-LBc)+(j-LBr)]
(column major order)
Where Base(A) = address of 1st element of A, w = Bytes per element
and M = total no. of rows in array UBr-LBr+1 /UB1-LB1+1
Find address of A[2,2] IN GIVEN ARRAY
Array of size 3x3 row index={0,1,2} Column index={0,1,2}
2006 2008 2010
2012 2014 2016
2018 2020 2022

Address calculation example


LBr=0, w=2, LBc=0 , Base=2006 j=2,k=2
In Row Measure
LOC (A[j,k])=Base(A)+w[(N(j-LBr)+(k-LBc)]
LOC(A[2,2])=2006+2x[3*(2-0)+(2-0)]
=2006+2x[8]
=2006+22
=2022 Ans.
Example 2
• Consider the 25 x 4 matrix array SCORE. Suppose Base(SCORE) = 200
& w= 4. Calculate the address of SCORE = [12,3] i.e. the 12th row and
3rd column using row major order and column major order. Assume
lower bound of row and column Both from 1.
Answer
• M = 25,
•N=4
• J = 12
• K=3
• W=4
• Base (SCORE) =200
Using Row-major order
• LOC (SCORE[12,3])
• Score(j,k) = Base(SCORE)+w[(N(j-LBr)+(k-LBc)]
= 200 + 4 [4(12-1) + (3-1)]
= 200 + 4 [4(11) + 2)]
= 200 + 4 [44 +2]
= 200 + 4 [46]
= 200 + 184
= 384
Using Column Major Order
• LOC (SCORE[12,3]) = Base(A)+w[(M(k-LBc)+(j-LBr)]
= 200 + 4 [25(3-1) + (12-1)]
= 200 + 4 [25(2) + 11)]
= 200 + 4 [50 +11]
= 200 + 4 [61]
= 200 + 244
= 444
Numerical Examples
• Consider a ARRAY A OF 4X4, with base address 1000, find the
location of a[4][3], a[2][4]. Assuming index start from 1
Solution
Consider an Array A*25…79, 55…124+,
BA=1000, w=10 find loc ( A[55][75])
Solution
Multidimensional Array
• When array can be extended to any number of
dimensions. E.g. 3D array may be defined as :
• int a[2][4][3]
• Multidimensional array also called arrays of arrays
• Suppose C is a 3D 2 x 4 x 3 array. Then C contains 2 x 4
x 3 = 24 elements. These elements appear in 3 layer
called pages, column and row.
• The length Li of dimension i of array is the number of elements in the
index set and Li can be calculated as
Li = upper boundi – lower boundi + 1
• For a given subscript Ki, the effective index Ei of Li is the number of
indices preceding Ki in the index set and Ei can be calculated from
Ei = Ki – lower boundi
• Then the address LOC(C[K1, K2, …….,KN]) of an arbitrary
element of C can be obtained from the formula
Row-Major
Base(C) + w [(…..((E1L2 + E2)L3+E3)L4+….. + EN-1)LN + EN)
LOC (A[j,k])=Base(A)+w[(N(j-LBr)+(k-LBc)]
(refer 2-d formula row major)
Column-Major
Base(C) + w [(…..((EN LN-1 + EN-1)LN-2+EN-2)+….. + E2)L1 + E1)
Base(A)+w[(M(k-LBc)+(j-LBr)]
• Where C is stored in column major or row major order.
Base (C) denotes the address of the first element of C and
w denotes the number of words per memory location.
Find address of A[1,1,1] IN GIVEN multi. Dim. ARRAY
Array of size 2x2x2,
Li = upper bound – lower bound + 1,
Ei = Ki – lower bound
2000 2002
2008 2010
2004 2006
2012 2014

E1=K1-0=1, E2=1-0=1, E3=1-0=1


L1=UB1-LB1+1=1-0+1=2
L2=2
L3=2
LOC (A[1,1,1])= Base(C) + w *(…..((E1L2 +
E2)L3+E3)L4+….. + EN-1)LN + EN)
=2000+2x[((1*2+1)*2+1)]
=2000+2x7
=2014 Ans.
Example
• Suppose a three-dimensional array MAZE is declared
using
MAZE (2:8, -4:1, 6:10)
• Suppose, MAZE in memory in row major order and
suppose Base(MAZE) = 200 and there are w =4 bytes
per element.
• Find out the address of an element of
• MAZE[5, -1, 8]
• Then the lengths of the 3D of MAZE are, respectively
• L1=8-2+1 ==7
• L2 = 1- (-4) + 1 = 6
• L3 = 10- 6 -1 = 5
• Accordingly MAZE contains L1.L2.L3 = 7.6.5 = 210 elements
• E1=5-2=3
• E2 = -1 -(-4) = 3
• E3 = 8-6 =2
• Using Eq. for row major order, we have
• E1L2 = 3.6 = 18
• E1L2 + E2 = 18 + 3 =21
• (E1L2 + E2)L3 = 21.5 = 105
• (E1L2+E2)L3 + E3 = 105 + 2 = 107
• LOC(MAZE[5, -1, 8]) = 200 + 4 (107)
• LOC(MAZE[5, -1, 8]) = 200 + 428 = 628
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?
Row Major: 2372
Column Major: 5240
A 2-D array defined as A[4.. 7, -1.. 3] requires 2 words of
storage space for each element if the array is stored in
row-major form calculate the address of A[6,2] given
the base address as 100(one hundred).
Solution
• sol:Base address B = 100
• Element size W = 2 bytes
• Lr = 4; Lc=-1; i =6; j=2
• n,number of rows=Ur -Lr + 1 =7 -4 + 1 = 4
• c,number of columns=Uc -Lc + 1 = 3-(-1)+1 = 5
• Address[I,J]=B+w(c(i-Lr) + (j -Lc))
• =100+2(5(6-4)+2-(1))=100+2(5*2+3)=100+2*(13)=100+26=126
• Each element of an array A[-20..20,10...35]
requires one byte of storage. if the array is stored in column
major order beginning location 500,determine the location
of A[0,30].
• Base address B =500
• Element size W = 1byter
• (number of rows) are 20 -(-20)+1=41 1
• lr = -20; lc =10
• Address of A[0,30] = 500 + 1[(0-(-20) +41(30-10))]= 500 +
(20+41*20)= 500 +1[20+820]= 500+840=1340
Passing Array to Functions
In a C program, you can pass
• an entire array to functions.
• an entire array to functions as a pointer.
• individual elements of an array to functions.
• address of individual array elements to functions.

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Example : Passing arrays to functions

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Example : Passing array to a function as a pointer

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Example : Passing individual array elements

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Example : Passing the address of individual array elements

DATA STRUCTURE (KCS-301)


(Mr Deepak Vishwakarma, Assistant Professor, IT, KIET)
Static Implementation of Data Structures
• Implementation of Data Structures at compile time is
known as Static Implementation
• The memory to be allocated to the variable is fixed
and is determined by the Compiler at the compile
time.
• e.g. Array
int a[5];
• Five memory locations will be allotted (each of 2
bytes for integer)

19-Sep-22 157
Problems of Static Implementation
1. There is no bound checking in C for array boundaries.
2. If you store less number of elements than the number of elements
for which you have declared memory, Then the rest of the memory
will be wasted

19-Sep-22 158
Dynamic Implementation of Data Structures
• Implementation of Data Structures at Run time is
known as Dynamic Implementation
• Problems of Arrays can be removed here
• We need not to know in advance, the size of
memory required
• C provides following functions:
1. malloc( )
2. calloc( )
3. free( )
4. realloc( )

19-Sep-22 159
Dynamic Implementation of Data Structures
(contd..)
1. malloc( ): It allocates a block of memory in bytes. It acts as a
request to RAM for allocation of memory. If request is granted then
it returns a pointer to the first block of that memory. The syntax is:
malloc(number of elements * size of each element);
e.g.
int *ptr;
ptr = malloc(10 * sizeof (int) );
Gives address of void type for first byte of allocated memory and NULL if could not
allocate.Type casting may required.
Availabe in alloc.h header file.
19-Sep-22 160
Similarly allocation of structure can be done
• struct student
• {
• int roll;
• char name[30];
• float percentage;
• };
• struct student *str_ptr
• st_ptr=(struct student *) malloc(sizeof(struct student));

if st_ptr==NULL ?????
Dynamic Implementation of Data Structures
(contd..)
2. calloc( ): This function works exactly similar to malloc( ) function
except for the fact that it needs two arguments as against one
argument by malloc( )
e.g.
int *ptr;
ptr = (int *) calloc (10,2);
• (int *) is the casting operator that will change the void to int type
pointer.
• Memory allocated by malloc( ) contains Garbage value, Whereas,
Memory allocated by calloc( ) contains all zeros.
19-Sep-22 162
Dynamic Implementation of Data Structures
(contd..)
3. Free( ): It is used to de-allocate the previously allocated memory
using malloc( ) or calloc( ) functions. The syntax is:
free ( ptr_var);

19-Sep-22 163
Dynamic Implementation of Data Structures
(contd..)
4. realloc( ): It is used to resize the size of memory block which is
already allocated. It found use of in two situations:
1. If the allocated memory block is insufficient for current application
2. If the allocated memory is much more than what is required by the current
application
The Syntax of this function:
ptr_var = realloc(ptr_var, new_size);

19-Sep-22 164
Sparse
Matrices:
Introduction
Memory Representations of sparse matrix
 Triplet Representation
 Linked List Representation
Classification of Sparse Matrix
 Triangular Matrices
 Band Matrix
What are SPARSE MATRICES?
 A matrix is a 2-dimensional data object composed of m rows and n columns, therefore
• having total m x n values.
 In computer programming, a matrix can be defined with a 2-dimensional array.
 Any array with 'm' rows and 'n' columns represent a m X n matrix.
 If most of the elements of the matrix have 0 value, then such a matrix is termed as
• “Sparse matrix”
┌ an example of a sparse
• Consider the following as ┐ matrix A:
| 10 0 3 0 0 0 |
| 21 2 0 4 0 0 |
| 0 3 6 0 5 0 |
| 0 0 23 24 0 26 |
| 81 0 0 94 65 0 |
| 71 92 0 0 55 36 |
└ ┘
Why to use Sparse Matrix?
• Storage: There are lesser non-zero elements than zeros and thus lesser memory can
be used to store only those elements.
– space calculation: Matrix having m rows and n columns the space required to store
the numbers will be m*n*s where s is the number of bytes required to store the
value.
E.g. Suppose there are 10 rows and 10 columns and we have to store the integer
values then the space complexity will be bytes.
10*10*2=200 bytes.
• Computing time: Computing time can be saved by logically designing a data
structure traversing only non-zero elements.
Sparse Matrix Representations
 Representing a sparse matrix with a 2D array results in wastage of memory and
processing time.
E.g. consider a matrix of size 100 X 100 containing only 10 non-zero elements.
– In this matrix, only 10 spaces are filled with non-zero values and remaining spaces of the
matrix are filled with zero.
– Space allocated: 100 X 100 X 2 = 20,000 bytes to store this integer matrix.
– Access time of 10 non-zero elements: 10,000 scans.

 To avoid such circumstances different techniques are used such as:


1) Triplet Representation (Array Representation)
2) Linked list representation
Method 1: Triplet Representation (Array
Representation)
• 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)
Triplet as - (Row, Column, value)

Consider the following as an example of a sparse matrix B:


Method 2: Linked List Representation
• 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
Classification of Sparse Matrix
Triangular Matrices Band Matrix
• Triangular matrices have the same number • A band matrix is a sparse matrix whose
of rows as they have columns; i.e. they non-zero entries are confined to a
have n rows and n columns. diagonal band, comprising the main
• Thus, triangular matrix is a special kind diagonal and zero or more diagonals on
of square matrix. either side. It can have different number of
rows and columns
Types of Triangular Matrices
Upper Triangular Matrices Lower Triangular Matrices

A matrix A is an upper triangular A matrix A is a lower triangular


matrix if its nonzero elements are matrix if its nonzero elements are
found only in the upper triangle of found only in the lower triangle of
the matrix, including the main the matrix, including the main
diagonal; diagonal;
Types of Band Matrices
Diagonal Matrix Tri-Diagonal Matrices
 Let A be a square matrix (with entries  A tri-diagonal matrix is a matrix that
in any field). If all off- diagonal has nonzero elements in the main
entries of A are zero, then A isa diagonal, the first diagonal below
diagonal matrix. this, and the first diagonal above the
Square diagonal matrix: main diagonal.

Rectangular diagonal matrix:


Disadvantages of Array
• The number of elements, which is to be stored in an
array must be known first.
• These are static structures. Static in the sense that
memory is allocated at compilation time.
• When an array is declared, memory is allocated to it.
If memory is not filled completely, the vacant place
occupies memory.
• The elements of the arrays are stored in consecutive locations, the
insertion and deletion into the array are time consuming. Because to
insert/delete an item require moving elements down to create a
space for new element or moving elements up to occupy the space by
the deleted element.
Linked List:
Need of Dynamic Data Structures
• A linked list is linear collection of data elements, called nodes ,
where linear order is given by means of pointers.
• Linked Lists are dynamic data structures: They can grow or
shrink during the execution of a program unlike arrays
• Efficient memory utilization: Memory is allocated whenever it
is required and deallocated when it is no longer needed unlike
arrays
• Insertion and Deletion are easier & efficient unlike arrays: It
provides flexibility in inserting a data item at a specified
position and deletion of a data item from the given position
• Many complex applications can be easily carried out with
linked list
A linked list node
• Each node contains a data item and a pointer to the next
node

data next next


• Data part contains the information to store.
Structure of a link
• Next node/ link part contain the pointer to next node.
list node:
• The last node has no next node
Struct Node
• An external pointer gives access to the first node
{ int info;
struct node *next;
first }
Linked list notation

node(p) Predecessor node(p) node(p) Successor

... ...

info(p) p next(p)
Accessing nodes in a linked list

first

• No direct access to individual nodes


• First node accessed via external pointer
• Other nodes accessed via pointer in previous node
• It is a sequential access data structure
Types of Linked Lists
1. Singly linked list
• Begins with a pointer to the first node
• Terminates with a null pointer
• Only traversed in one direction
2. Circular, singly linked
• Pointer in the last node points back to the first node
3. Doubly linked list
• Two “start pointers” – first element and last element
• Each node has a forward pointer and a backward pointer
• Allows traversals both forwards and backwards
4. Circular, doubly linked list
• Forward pointer of the last node points to the first node and backward
pointer of the first node points to the last node
Operation on Lists
1. Creation
2. Insertion
3. Deletion
4. Traversal
5. Searching
6. Display
Singly Linked List
• A singly linked list is a concrete
data structure consisting of a next
sequence of nodes
• Each node stores
• element
• link to the next node
elem node

head

A B C

A B C D
Creation of single
node.

Head NULL

30
data next NULL

n( address of new node)


Creation of single node.

Head NULL

30
data next NULL

n( address of new node)


• Infer the output.
Head NULL

data next NULL

n( address of new node)


Create_node(): Whenever need a singly linked list node call
this function
TRAVERSING A LINKED LIST
1. Set START = HEAD
2. Repeat steps 3 and 4 while START!=NULL
3. Apply PROCESS to DATA[START]
4. Set START=NEXT[START]
5. Exit
Insertion at end
• Three steps:
• find node after which to add
• Allocate space for a node and store data in it
• Link the new node into the existing linked list
Insertion at end
Inserting at the Beginning
Inserting at the
Beginning (Algo.)
INSERT_BEGINING(INFO,LINK,HEAD,AVAIL,ITEM,HEAD)
1. IF AVAIL=NULL then Write OVERFLOW and EXIT.
2. TEMP=AVAIL and AVAIL=LINK[AVAIL]
3. INFO[NEW]=ITEM
4. IF HEAD =NULL Then
HEAD=TEMP
ELSE
NEXT[TEMP]=HEAD
HEAD=TEMP
6. EXIT.
Head
Head
Finding length
Illustration: Insert after A
A B C

tmp X Item to be
inserted

A B C

curr

'' 194
Inserting after a given Node/LOC
Deleting the Element(From Beginning)
Head
2000
1000

45 2000 15 4000 25 NULL

1000 2000 4000


Head
2000
1000

temp
45 2000 15 4000 25 NULL
1000

1000 2000 4000


Delete a given Node number(Let say 2)can
also use for last node
• q=p->next Head
1000 NULL
4000

p(initially)
45 2000 15 4000 25 NULL
1000

1000 2000 4000


q=p->next Free this Node

2000 Node-1 Node-2 Node-3

Increment p to q will
q->next is 4000 reach at location hold
before the node to address
delete of node
Deleting the Specific Node,Need 2 Pointers?
Head
• q=p->next

1000 NULL
4000

p(initially)
45 2000 15 4000 25 NULL
1000

1000 2000 4000


q=p->next Free this Node

Node-1 Node-2 Node-3


2000
Increment p to reach at q will hold
location before the address of
q->next is 4000 node to delete node to
delete
SEARCH(INFO,LINK,START,ITEM, LOC)
• 1. SET PTR=START
• 2. REPEAT STEP-3 WHILE PTR!=NULL:
• 3. IF ITEM=INFO[PTR], THEN:
• SET LOC=PTR AND EXIT
• ELSE:
• SET PTR=LINK[PTR]
• 4. SEARCH FAIL. SET LOC=NULL
• EXIT
Reverse of link list:
• Initialize three pointers prev as NULL, curr as head and next as NULL.
• Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next // Now change next of current
// This is where actual reversing happens
curr->next = prev
• // Move prev and curr one step forward
prev = curr
curr = next
Reverse of linked list
Circular Lists
• The last node contains pointer to the first node of the list
• We can begin at any node and traverse the list until we reach the
same node where we started

A B C

START
Inserting the at beginning of Circular linked
list

A B C

START

E NULL

New Node
Inserting an element in the beginning of a Circular
List
1. If AVAIL==NULL then Write Overflow and Return
2. Set NEW=AVAIL and AVAIL=LINK[AVAIL]
3. INFO[NEW]=ITEM
4. Set PTR=START
5. Repeat Step 6 while LINK[PTR]!=START
6. PTR=LINK[PTR]
7. Set LINK[NEW]=START
8. Set LINK[PTR]=NEW
9. Set START=NEW
10. Exit
Inserting an element at the end of a Circular List

1. If AVAIL==NULL then Write Overflow


and Return
2. Set NEW=AVAIL
3. Set INFO[NEW]=ITEM
4. Set PTR=START
5. Repeat Step 7 while
LINK[PTR]!=START
6. PTR=LINK[PTR]
7. Set LINK[PTR]=NEW
8. LINK[NEW]=START

9. Exit
Deleting the First node from Circular List

1. If START==NULL then Write Underflow and Return


2. Set PTR=START
3. Repeat STEP 4 while LINK[PTR]!=START
4. Set PTR=LINK[PTR]
5. Set LINK[PTR]=LINK[START]
6. TEMP =START
7. Free TEMP TO AVAIL
8. START=LINK[PTR]
9. Exit
Deleting the Last node from Circular List

1. If START==NULL then Write Underflow and Return


2. Set PTR=START
3. Repeat STEP 4 while LINK[PTR]!=START
4. Set SAVE=PTR and PTR=LINK[PTR]
5. Set LINK[SAVE]=START
6. Free PTR to Avail
7. Exit
Node of doubly Linked List
• A new node of DLL

*Prv Data *next

NULL 30 NULL
Create_Node() for DLL Node
n=3000(New node address)

NULL 30 NULL
Inserting a new node at the end
Null NULL 30 NULL 4000 NULL 30 NULL

Head temp=3000 Head p=4000


NULL 30 NULL
Empty List Existing List
temp=3000
1. Temp=create_node()
2. If Head=NULL
head=temp
else
PTR=Head
while PTR[next]!=NULL
PTR=PTR[Next]
3. PTR[next]=temp
4. Temp[Prv]=PTR
5. Exit
Inserting a new node at the end
3000 NULL 30 NULL 3000 NULL 30 4000

Head temp=3000 Head p=3000


3000 30 NULL
Empty List Existing List
temp=4000
1. Temp=create_node()
2. If Head=NULL
head=temp
else
PTR=Head
while PTR[next]!=NULL
PTR=PTR[Next]
3. PTR[next]=temp
4. Temp[Prv]=PTR
5. Exit
Finding length of Double Linked List
Traversing in forward direction
Temp=head
Head While temp!=Null, move forward using
forward pointers. And display temp->data

Reached till end,


and stop
Traverse in
forward
direction
Traversing in Backward
Head
While temp->next!=Null, move forward using
forward pointers.

Last element not


traversed, print Reached till end,
separately. and start
backward
traversal, till
temp->Prv!=head
Traverse in
reverse
direction
Add_DLL Node
at Beginning
Add at specific position(Core idea)
• Reach before specific position(p) through forward pointer.
• Take the reference of newly created node in temp
• temp->next=p->next
• p->next->prv=temp
• temp->prv=p
• p->next=temp
Delete from
Beginning
Doubly Linked List
• A Doubly linked list is a two way linked list, where each node N is divided into three
parts:
1. An information field INFO which contains the data of N
2. A pointer FORW which contains the location of the next node in the list
3. A pointer field BACK which contains the location of the preceding node in the list
4. The BACK pointer of first node and the FORW pointer of the last node will contain
NULL

You might also like