SlideShare a Scribd company logo
1 of 231
Noida Institute of Engineering and
Technology, Greater Noida
Introduction to Arrays and Linked List
Megha Gupta
Assistant Professor
Computer Science and
Engineering
Unit: 1
Data Structure
Course Details
(Ex: B Tech 3th Sem)
• Be familiar with basic techniques of algorithm analysis
• Be familiar with writing recursive methods
• Master the implementation of linked data structures such as linked lists
and binary trees
• Be familiar with advanced data structures such as balanced search
trees, hash tables, priority queues and the disjoint set union/find data
structure
• Be familiar with several sub-quadratic sorting algorithms including
quicksort, mergesort and heapsort
7/4/2020 Megha Gupta KCS 301: DS Unit 1 2
Course Objective
• Be familiar with some graph algorithms such as shortest path and
minimum spanning tree
• Master the standard data structure library of a major programming
language
• Master analyzing problems and writing program solutions to problems
using the above techniques
7/4/2020
Megha Gupta KCS 301: DS Unit 1
3
Course Objective
• CO 1 Describe how arrays, linked lists, stacks, queues, trees, and
graphs are represented in memory, used by the algorithms and
their common applications.
• CO 2 Identify the alternative implementations of data structures
with respect to its performance to solve a real world problem.
• CO 3 Understanding the concept of recursion, application of
recursion and its implementation and removal of recursion.
• CO 4 Discuss the computational efficiency of the sorting and
searching algorithms.
• CO 5 Implementation of Trees and Graphs and perform various
operations on these data structure.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 4
Course Outcome
1.Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization for the
solution of complex engineering problems.
2.Problem analysis: Identify, formulate, research literature, and analyse
complex engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering
sciences.
3.Design/development of solutions: Design solutions for complex
engineering problems and design system components or processes that
meet the specified needs with appropriate consideration for public health
and safety, and cultural, societal, and environmental considerations.
4.Conduct investigations of complex problems: Use research based
knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of information to
provide valid conclusions.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 5
Program Outcomes
5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools, including prediction and
modeling to complex engineering activities, with an understanding of the
limitations.
6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and
the consequent responsibilities relevant to the professional engineering
practice.
7. Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable
development.
8.Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 6
Program Outcomes
9. Individual and team work: Function effectively as an individual, and as
a member or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering
activities with the engineering community and with the society at large,
such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions.
11. Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation
and ability to engage in independent and life-long learning in the
broadest context of technological change.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 7
Program Outcomes
On successful completion of graduation degree the Computer Science &
Engineering graduates will be able to:
PSO1: The ability to design and develop the Hardware and Software
systems.
PSO2: An understanding of interdisciplinary computing techniques and an
ability to apply them in the design of advanced computing.
PSO3: An understanding of programming methodology software
development paradigms, design and analysis of Algorithms, Operating
Systems, Digital Logic Design, Theory of Computation, Discrete
Mathematics, Compiler Design, etc.
PSO4: The ability to integrate & manage the various phases/components
of software development projects of society.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 8
Program Specific Outcomes
• PEO 1: To have an excellent scientific and engineering breadth so as
to comprehend, analyze, design and solve real-life problems using
state-of-the-art technologies.
• PEO 2: To lead a successful career in industries, to pursue higher
studies or to support entrepreneurial endeavors so that engineering
graduates can face the global challenges.
• PEO 3: To effectively bridge the gap between industry and academia
through effective communication skill, professional attitude, ethical
values and a desire to learn.
• PEO 4: To provide highly competitive environment and solidarity to
students for successful professional career as engineer, scientist,
entrepreneur and bureaucrats for the betterment of society.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 9
Program Education Objectives
Sr.
No Course
Outcome
PO1
PO2
PO3
PO4
PO5
PO6
PO7
PO8
PO9
PO10
PO11
PO12
1 CO 1 3 3 3 3 3 2 1 1 3 2 2 1
2 CO 2 3 3 3 3 3 2 1 1 3 1 2 1
3 CO 3 3 3 3 3 3 2 1 1 3 1 2 1
4 CO 4 3 3 3 3 3 2 1 1 3 1 2 1
5 CO 5 3 3 3 3 3 2 1 1 3 1 2 1
7/4/2020 Megha Gupta KCS 301: DS Unit 1 10
CO-PO Mapping
Sr.
No Course Outcome
PSO1
PSO2
PSO3
PSO4
1 CO 1 3 2 3 3
2 CO 2 2 3 2 3
3 CO 3 2 2 3 2
4 CO 4 2 2 3 1
5 CO 5 3 1 3 2
7/4/2020 Megha Gupta KCS 301: DS Unit 1 11
CO-PSO Mapping
• Introduction: Basic Terminology, Elementary Data Organization,
Built in Data Types in C.
• Algorithm, Efficiency of an Algorithm, Time and Space Complexity,
Asymptotic notations: Big
• Oh, Big Theta and Big Omega, Time-Space trade-off. Abstract Data
Types (ADT)
• Arrays: Definition, Single and Multidimensional Arrays,
Representation of Arrays: Row Major
• Order, and Column Major Order, Derivation of Index Formulae for 1-
D,2-D,3-D and n-D Array
• Application of arrays, Sparse Matrices and their representations.
UNIT-1
Syllabus
7/4/2020 Megha Gupta KCS 301: DS Unit 1 12
• Linked lists: Array Implementation and Pointer Implementation of
Singly Linked Lists, Doubly
• Linked List, Circularly Linked List, Operations on a Linked List.
Insertion, Deletion, Traversal,
• Polynomial Representation and Addition Subtraction &
Multiplications of Single variable & Two
• variables Polynomial.
UNIT-1
Syllabus
7/4/2020 Megha Gupta KCS 301: DS Unit 1 13
Topics Duration (in
Hours)
Basic Terminology 1
Elementary Data Organization
Built in Data Types in C.
1
Algorithm, Efficiency of an Algorithm 1
Time and Space Complexity 1
Asymptotic notations: Big Oh, Big Theta and Big
Omega
1
Time-Space trade-off. 1
Abstract Data Types (ADT) 1
Arrays 1
Single and Multidimensional Arrays 1
Contents
7/4/2020 Megha Gupta KCS 301: DS Unit 1 14
Topics Duration (in
Hours)
Representation of Arrays: Row Major Order, and
Column Major Order
1
Derivation of Index Formulae for 1-D,2-D,3-D and n-D
Array
1
Sparse Matrices and their representations. 1
Representation of Arrays: Row Major Order, and
Column Major Order
1
Derivation of Index Formulae for 1-D,2-D,3-D and n-D
Array
1
Sparse Matrices and their representations. 1
Contents
7/4/2020 Megha Gupta KCS 301: DS Unit 1 15
Topics Duration (in
Hours)
Linked lists: Array Implementation
Pointer Implementation of Singly Linked Lists
1
Doubly Linked List 1
Circularly Linked List 1
Polynomial Representation 1
Contents
7/4/2020 Megha Gupta KCS 301: DS Unit 1 16
Objective of the course is to make students able to:
• Learn the basic types for data structure, implementation and
application.
• Know the strength and weakness of different data structures.
• Use the appropriate data structure in context of solution of given
problem
• Develop programming skills which require to solve given problem.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 17
Objective of Unit
• Repetition statements (loops)-while, for, do-while statements, Loop
examples
• Functions-Designing Structured Programs, Functions, user defined
functions.
• Pointers – Introduction (Basic Concepts), Pointers for inter function
communication, pointers to pointers, compatibility, Pointer
Applications-Arrays and Pointers, Pointer Arithmetic and arrays,
Passing an array to a function, memory allocation functions, array
of pointers, programming applications.
• Basics of Structures, Arrays of Structures, Pointers to Structures,
Self-referential Structures.
• Dynamic Memory Allocation, Allocating Memory with malloc,
Allocating Memory with calloc, Freeing Memory, Reallocating
Memory Block
7/4/2020 Megha Gupta KCS 301: DS Unit 1 18
Prerequisite and Recap
Topic mapping with Course Outcome
7/4/2020 19
Array and Linked List(CO1)
Topic CO1 CO2 CO3 CO4 CO5
Array 1 - - - -
Linked List 1 - - - -
Megha Gupta KCS 301: DS Unit 1
Basic Terminologies
• Data: are simply a value are set of values of different type which is
called data types like string, integer, char etc.
• Structure: Way of organizing information, so that it is easier to use.
• In simple words we can define DATA STRUCTURES as its a way
organizing data in such a way so that data can be easier to use.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 20
Introduction
Definition
• Data Structure ..
A data structure is a particular way of organizing data in a computer
so that it can be used efficiently.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 21
Introduction
Why Data Structure
7/4/2020 Megha Gupta KCS 301: DS Unit 1 22
Introduction
Why Data Structure
• Human requirement with computer are going to complex day by
day. To solve the complex requirements in efficient way we need
this study.
• Provide fastest solution of human requirements.
• Provide efficient solution of complex problem.
>Space
>Time
7/4/2020 Megha Gupta KCS 301: DS Unit 1 23
Introduction
Classification of Data Structure
7/4/2020 Megha Gupta KCS 301: DS Unit 1 24
Introduction
Classification of Data Structure ...
• Simple Data Structure / Primitive data structure: used to
represent the standard data types of any one of the computer
languages (integer, Character, float etc.).
• Compound Data Structure / Non Primitive Data Structure: can
be constructed with the help of any one of the primitive data structure
and it is having a specific functionality. It can be designed by user. It
can be classified as Linear and Non-Linear Data Structure.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 25
Introduction
Classification of Data Structure ...
• Linear Data Structures: A linear data structure traverses the data
elements sequentially, in which only one data element can directly
be reached. Ex: Arrays, Linked Lists.
• Non-Linear Data Structures: Every data item is attached to
several other data items in a way that is specific for reflecting
relationships. The data items are not arranged in a sequential
structure. Ex: Trees, Graphs
7/4/2020 Megha Gupta KCS 301: DS Unit 1 26
Introduction
Operation on Linear/Non-Linear Data Structure
• Add an element
• Delete an element
• Traverse / Display
• Sort the list of elements
• Search for a data element
7/4/2020 Megha Gupta KCS 301: DS Unit 1 27
Introduction
Types of Linear Data Structure
• Array: An array is the collection of the variables of the same data
type that are referenced by the common name.
• int A[10], char B[10]
7/4/2020 Megha Gupta KCS 301: DS Unit 1 28
Introduction
Types of Linear Data Structure….
• Stack
Stack is a linear data structure in which the
insertion and deletion operations are performed
at only one end. In a stack, adding and removing
of elements are performed at a single position
which is known as “top”. That means, a new
element is added at top of the stack and an
element is removed from the top of the stack. In
stack, the insertion and deletion operations are
performed based on LIFO(Last In First Out)
principle.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 29
Introduction
Types of Linear Data Structure…
• Queue is a linear data structure in which the
insertion and deletion operations are
performed at two different ends.
• The insertion is performed at one end and
deletion is performed at another end.
• In a queue data structure, the insertion
operation is performed at a position which is
known as “rear” and the deletion operation is
performed at a position which is known as
'front'.
• In queue data structure, the insertion and
deletion operations are performed based on
FIFO (First In First Out) principle.7/4/2020
Megha Gupta KCS 301: DS Unit 1
30
Introduction
Types of Linear Data Structure…
• LINKED LIST
When we want to work with an unknown number of data values,
we use a linked list data structure to organize that data.
The linked list is a linear data structure that contains a sequence of
elements such that each element links to its next element in the
sequence. Each element in a linked list is called "Node".
7/4/2020 Megha Gupta KCS 301: DS Unit 1 31
Introduction
Types of NON Linear Data Structure
• Tree is a non-linear data
structure which organizes data in
hierarchical structure.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 32
Introduction
Types of NON Linear Data Structure..
• Graph is a non-linear data structure. It
contains a set of points known as nodes
(or vertices) and a set of links known as
edges (or Arcs). Here edges are used to
connect the vertices.
• Generally, a graph G is represented as G
= ( V , E ), where V is set of
vertices and E is set of edges.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 33
Introduction
What is an Array
• An array is the collection of the variable of the same type that are
referenced by the common name.
• An array is the derived data type.
• Consist of contiguous memory locations.
• Lowest address corresponds to first element while highest address
corresponds to last element.
• Can have data item of type int, float, char, double etc. also have
user derived data type like: structure, union.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 34
Introduction to Array
Need for an Array
• To store large number of array of variables of same type under a
single variable.
• Eg.
To store Marks of 50 Students
Record of sales of 100 salesman
7/4/2020 Megha Gupta KCS 301: DS Unit 1 35
Introduction to Array
Types of Arrays in C
• In c programming language, arrays are classified into two types. They are
as follows...
> Single Dimensional Array / One Dimensional Array
> Multi Dimensional Array
Declaration of Single Dimensional Array
• datatype arrayName [ size ] ;
• int rollNumbers [60] ;
Initialization of Single Dimensional Array
• datatype arrayName [ size ] = {value1, value2, ...} ;
• int marks [6] = { 89, 90, 76, 78, 98, 86 } ;
• int marks [] = { 88,96,89, 90, 76, 78, 98, 86 } ;
Accessing Elements of Single Dimensional Array
A[2]=99;
7/4/2020 Megha Gupta KCS 301: DS Unit 1 36
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 37
Introduction to Array
• Array of an element of an array say “A[ I ]” is calculated using the
following formula:
• Address of A [ I ] = B + W * ( I – LB )
• Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume
0 (zero)
7/4/2020 Megha Gupta KCS 301: DS Unit 1 38
Introduction to Array
Example:
• Given the base address of an array B[1300…..1900] as 1020 and size
of each element is 2 bytes in the memory. Find the address
of B[1700].
• Solution:
The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [ I ] = B + W * ( I – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]
7/4/2020 Megha Gupta KCS 301: DS Unit 1 39
Introduction to Array
• Find the base address of an array A[-15:65]. The size of each
element is 2 bytes in the memory and the location of A[37] is 4279.
Solution:
The given values are: LB = -15, UB = 65, W = 2, I = 37, A[37] = 4279
Address of A [ I ] = B + W * ( I – LB )
4279= B + 2 * (37 – (-15))
4279= B + 2 * 52
4279= B + 104
B= 4175 [Ans]
7/4/2020 Megha Gupta KCS 301: DS Unit 1 40
Introduction to Array
Creating an array in C
#include<stdio.h>
void main()
{
int a[10],i,n;
printf("nEnter number of elements");
scanf("%d",&n);
printf("n Enter %d elementsn",n);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(i=0;i<n;i++){
printf("n%d",a[i]);
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 41
Introduction to Array
Passing array to function
• Passing array to function using call by value method.
• Passing array to function using call by reference.
• Passing entire array to a function as an argument.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 42
Introduction to Array
Passing array to function using call by value method
#include <stdio.h>
void disp( char ch) {
printf("%c ", ch);
}
void main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++) {
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 43
Introduction to Array
Passing array to function using call by reference
#include <stdio.h>
void disp( int *num) {
printf("%d ", *num);
}
void main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++) {
/* Passing addresses of array elements*/
disp (&arr[i]);
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 44
Introduction to Array
Passing an entire array to a function
#include <stdio.h>
float average(float age[]);
int main()
{
float avg, age[] = {23.4, 55, 22.6, 3,
40.5, 18};
avg = average(age);
//Only name of an array is passed
//as an argument
printf("Average age = %.2f", avg);
return 0;
}
float average(float age[])
{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 45
Introduction to Array
Write a program in c to find max element in the array
using function.
#include <stdio.h>
#include <conio.h>
int max(int [],int);
void main()
{
int a[]={10,5,45,12,19};
int n=5,m;
clrscr();
m=max(a,n);
printf("nMAXIMUM NUMBER
IS %d",m);
getch();
}
int max(int x[],int k)
{
int t,i;
t=x[0];
for(i=1;i<k;i++)
{
if(x[i]>t)
t=x[i];
}
return(t);
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 46
Introduction to Array
Searching For an Element in an Array
• There are two ways to search an element:
Linear Search
> Check each element of an array.
> If the match found – element exists, else does not exist.
> Suitable for small lists since time consuming
> Suitable for unsorted Lists.
Binary Search
> Most Important preconditions is that the list should be
sorted.
> Suitable for arrays with long list of elements
7/4/2020 Megha Gupta KCS 301: DS Unit 1 47
Introduction to Array
Linear Search
• The linear search is a sequential search, which uses a loop to step
through an array, starting with the first element.
• It compares each element with the value being searched for, and stops
when either the value is found or the end of the array is encountered.
• If the value being searched is not in the array, the algorithm will
unsuccessfully search to the end of the array.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 48
Introduction to Array
Advantages
• The linear search is simple - It is very easy to understand and
implement.
• It does not require the data in the array to be stored in any
particular order.
Disadvantages
• It has very poor efficiency because it takes lots of comparisons to
find a particular record in big files.
• The performance of the algorithm scales linearly with the size of
the input .
• Linear search is slower then other searching algorithms.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 49
Introduction to Array
Linear Search Example
7/4/2020 Megha Gupta KCS 301: DS Unit 1 50
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 51
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 52
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 53
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 54
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 55
Introduction to Array
#include <stdio.h>
int search(int arr[], int n, int x) ;
void main( )
{ int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, n, x);
(result == -1) ? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 56
Introduction to Array
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 57
Introduction to Array
Analysis of Linear Search
How long will our search take?
• In the best case, the target value is in the first element of the
array.
So the search takes some tiny, and constant, amount of time.
• In the worst case, the target value is in the last element of the
array.
So the search takes an amount of time proportional to the
length of the array. O(n)
7/4/2020 Megha Gupta KCS 301: DS Unit 1 58
Introduction to Array
Analysis of Linear Search
• In the average case, the target value is somewhere in the array.
• In fact, since the target value can be anywhere in the array, any
element of the array is equally likely.
• So on average, the target value will be in the middle of the array.
• So the search takes an amount of time proportional to half the
length of the array.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 59
Introduction to Array
Binary Search
The general term for a smart search through sorted data is a binary
search.
1. The initial search region is the whole array.
2. Look at the data value in the middle of the search region.
3. If you’ve found your target, stop.
4. If your target is less than the middle data value, the new search
region is the lower half of the data.
5. If your target is greater than the middle data value, the new
search region is the higher half of the data.
6. Continue from Step 2.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 60
Introduction to Array
Binary Search Example
7/4/2020 Megha Gupta KCS 301: DS Unit 1 61
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 62
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 63
Introduction to Array
#include <stdio.h>
void main()
{
int c, first, last, middle, n, search,
array[100];
printf("Enter number of
elements:n");
scanf("%d",&n);
printf("Enter %d integers:n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter the value to find:n");
scanf("%d", &search);
first = 0;last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d is present at index %d.n",
search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not
present in the list.n", search); }
Binary Search Program
7/4/2020 Megha Gupta KCS 301: DS Unit 1 64
Introduction to Array
Time complexity of binary search
At each iteration, the array is divided by
half. So let’s say the length of array at any
iteration is n
At Iteration 1,
Length of array = n
At Iteration 2,
Length of array = n⁄2
At Iteration 3,
Length of array = (n⁄2)⁄2 = n⁄22
Therefore, after Iteration k,
Length of array = n⁄2k
Also, we know that after
After k divisions, the length
of array becomes 1
Therefore
Length of array = n⁄2k = 1
=> n = 2k
Applying log function on both
sides:
=> log2 (n) = log2 (2k)
=> log2 (n) = k log2 (2)
=> k = log2 (n)
Hence the time complexity of
Binary Search is
log2 (n)
7/4/2020 Megha Gupta KCS 301: DS Unit 1 65
Introduction to Array
Insert element in array
• Example
• Input
Input array elements: 10, 20, 30, 40, 50
Input element to insert: 35
Input position where to insert: 4
Output
Elements of array are: 10, 20, 30, 35, 40, 50
7/4/2020 Megha Gupta KCS 301: DS Unit 1 66
Introduction to Array
Logic to insert element in array
Insert an element at position 4.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 67
Introduction to Array
Logic to insert element in array
for(i=size; i>=pos; i--)
arr[i] = arr[i - 1];
7/4/2020 Megha Gupta KCS 301: DS Unit 1 68
Introduction to Array
arr[pos - 1] = num;
7/4/2020 Megha Gupta KCS 301: DS Unit 1 69
Introduction to Array
Program to insert element in array
#include <stdio.h>
#define MAX_SIZE 100
int main()
{ int arr[MAX_SIZE];
int i, size, num, pos;
printf("Enter size of the array :
");
scanf("%d", &size);
printf("Enter elements in array
: ");
7/4/2020
Megha Gupta KCS 301: DS Unit 1
70
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position :
");
scanf("%d", &pos);
if(pos > size+1 || pos <= 0)
{ printf("Invalid position! Please
enter position between 1 to %d",
size);
}
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 71
else
{
/* Make room for new array
element by shifting to right */
for(i=size; i>=pos; i--)
{
arr[i] = arr[i-1];
}
/* Insert new element at given
position and increment size */
arr[pos-1] = num;
size++;
/* Print array after insert
operation */
printf("Array elements after
insertion : ");
for(i=0; i<size; i++)
{
printf("%dt", arr[i]);
}
}
return 0;
}
Introduction to Array
Delete element from an array
• Example
• Input
Input array elements: 10 20 30 40 50
Input position to delete: 2
Output
Array elements: 10, 30, 40, 50
7/4/2020 Megha Gupta KCS 301: DS Unit 1 72
Introduction to Array
Logic to remove element from array
•Step by step descriptive logic to
remove element from array.
•Move to the specified location
which you want to remove in given
array.
•Copy the next element to the
current element of array. Which is
you need to perform array[i] =
array[i + 1].
•Repeat above steps till last element
of array.
•Finally decrement the size of array
by one.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 73
Introduction to Array
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int i, size, pos;
printf("Enter size of the array : ");
scanf("%d", &size);
printf("Enter elements in array : ");
for(i=0; i<size; i++)
{ scanf("%d", &arr[i]);
}
Program to delete an element from an array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 74
Introduction to Array
printf("Enter the element position
to delete : ");
scanf("%d", &pos);
if(pos < 0 || pos > size)
{ printf("Please enter position
between 1 to %d", size);
}
else
{
for(i=pos; i<=size-1; i++){
arr[i-1] = arr[i];
}
size--;
}
printf("nElements of array after delete are : ");
for(i=0; i<size; i++) {
printf("%dt", arr[i]);
}
return 0;
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 75
Introduction to Array
Multi-dimensional Arrays in C
• Multidimensional array declaration
type name[size1][size2]...[sizeN];
• For example, the following declaration creates a three dimensional
integer array −
int threedim[5][10][4];
7/4/2020 Megha Gupta KCS 301: DS Unit 1 76
Introduction to Array
Two dimensional (2D) arrays
• An array of arrays is known as 2D array.
• The two dimensional (2D) array in C programming is also known
as matrix.
• A matrix can be represented as a table of rows and columns.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 77
Introduction to Array
Initializing Two-Dimensional Arrays
• Multidimensional arrays may be initialized by specifying bracketed
values for each row. Following is an array with 3 rows and each row
has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
• The nested braces, which indicate the intended row, are optional.
The following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
7/4/2020 Megha Gupta KCS 301: DS Unit 1 78
Introduction to Array
Things that you must consider while initializing a 2D
array
• /* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
• /* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
• /* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
• /* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
7/4/2020 Megha Gupta KCS 301: DS Unit 1 79
Introduction to Array
Accessing Two-Dimensional Array Elements
• An element in a two-dimensional array is accessed by using the
subscripts, i.e., row index and column index of the array.
For example : int val = a[2][3];
#include <stdio.h>
void main () {
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %dn", i,j, a[i][j] );
}
}
} 7/4/2020 Megha Gupta KCS 301: DS Unit 1 80
Introduction to Array
To store the elements entered by user in 2D Array
#include<stdio.h>
void main()
{
int abc[5][4];
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
}7/4/2020 Megha Gupta KCS 301: DS Unit 1 81
Introduction to Array
Address Calculation in Two Dimensional Array:
7/4/2020 Megha Gupta KCS 301: DS Unit 1 82
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 83
Introduction to Array
Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as
given:
Row Major System:
Address of A [ I1 ][ I2 ] = B + W * [( I1 – L1 ) * N2+ ( I2 – L2 )]
Column Major System:
Address of A [ I1 ][ I2 ] Column Major Wise = B + W * [( I1 – L1 ) + N1 * ( I2 – L2 )]
Where,
B = Base address
I1 = Row subscript of element whose address is to be found
I2 = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
L1 = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
L2 = Lower limit of column/start column index of matrix, if not given assume 0
(zero)
N1 = Number of row of the given matrix
N2 = Number of column of the given matrix7/4/2020 Megha Gupta KCS 301: DS Unit 1 84
Introduction to Array
Q 1. An array X [-15……….10, 15……………40] requires one byte of storage. If
beginning location is 1500 determine the location of X [15][20].
As you see here the number of rows and columns are not given in the
question. So they are calculated as:
Number or rows say N1 = (U1 – L1) + 1 = [10 – (- 15)] +1 = 26
Number or columns say N2 = (U2 – L2) + 1 = [40 – 15)] +1 = 26
(i) Column Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I1 = 15, I2 = 20, L1 = -15, L2 =
15, N1 = 26
Address of A [ I1 ][ I2 ] =B + W * [( I1 – L1 ) + N1 * ( I2 – L2 )]
= 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)] = 1500 + 1 * [30 + 26 * 5] =
1500 + 1 * [160] = 1660 [Ans]
7/4/2020 Megha Gupta KCS 301: DS Unit 1 85
Introduction to Array
Q 1. An array X [-15……….10, 15……………40] requires one byte of storage. If
beginning location is 1500 determine the location of X [15][20].
(ii) Row Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I1 = 15, I2 = 20, L1 = -15, L2 =
15, N2 = 26
Address of A [ I1 ][ I2 ] =B + W * [( I1 – L1 )* N2 + ( I2 – L2 )]
= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)] = 1500 + 1 * [26 * 30 + 5] =
1500 + 1 * [780 + 5] = 1500 + 785
= 2285 [Ans]
7/4/2020 Megha Gupta KCS 301: DS Unit 1 86
Introduction to Array
Three-Dimensional Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 87
Introduction to Array
Given an array [ 1..8, 1..5, 1..7 ] of integers. Calculate address of element
A[5,3,6], by using rows wise methods, if Base Address=900?
Solution:- The dimensions of A are :
N1=8 , N2=5, N3=7, I1=5, I2=3, I3=6, W=2,L1=1,L2=1,L3=1
Rows - wise :
Location (A[I1, I2, I3]) = B + W*[(E1N2+E2)*N3+E3]
= B + W*[((I1-L1)*N2+(I2-L2))*N3+(I3-L3)]
Location(A[5,3,6])= 900 + 2*[((5-1)*5+(3-1))*7+(6-1)]
= 900 + 2*[(4*5+2)*7+5]
= 900 +2*159
= 1218
7/4/2020 Megha Gupta KCS 301: DS Unit 1 88
Introduction to Array
Initializing Three-Dimensional Array
Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23};
Method 2:
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
7/4/2020 Megha Gupta KCS 301: DS Unit 1 89
Introduction to Array
Applications of Arrays in C
● Arrays are used to Store List of values
● Arrays are used to Perform Matrix Operations
● Arrays are used to implement Search Algorithms
Linear Search Binary Search
● Arrays are used to implement Sorting Algorithms.
Insertion Sort Bubble Sort
Selection Sort Quick Sort Merge Sort, etc.,
● Arrays are used to implement Data structures.
Stack Using Arrays Queue Using Arrays
● Arrays are also used to implement CPU Scheduling Algorithms.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 90
Introduction to Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 91
Sorting Using Array
Bubble Sort is the simplest sorting algorithm that works by
repeatedly swapping the adjacent elements if they are in wrong
order.
Bubble Sort
7/4/2020 Megha Gupta KCS 301: DS Unit 1 92
Bubble sort Illustration
Sorting Using Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 93
C Program for Bubble Sort
Sorting Using Array
// A function to implement
bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already
in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 94
// Driver program to test above
functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11,
90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}
C Program for Bubble Sort
Sorting Using Array
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
Insertion Sort Example
7/4/2020 Megha Gupta KCS 301: DS Unit 1 95
Sorting Using ArraySorting Using Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 96
Sorting Using Array
7/4/2020 Megha Gupta KCS 301: DS Unit 1 97
Sorting Using Array
#include <math.h>
#include <stdio.h>
/* Function to sort an array using
insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1],
that are
greater than key, to one
position ahead
of their current position */
while (j >= 0 && arr[j] >
key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 98
Sorting Using Array
// A utility function to print an array
of size n
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("n");
}
/* Driver program to test insertion
sort */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) /
sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part
and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering
ascending order) from the unsorted subarray is picked and moved to
the sorted subarray.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 99
Sorting Using Array
Selection Sort
7/4/2020 Megha Gupta KCS 301: DS Unit 1 100
Sorting Using Array
Selection Sort Example
7/4/2020 Megha Gupta KCS 301: DS Unit 1 101
Sorting Using Array
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of
unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element
in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum
element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
C Program for Selection Sort
Sparse Matrix
• Any matrix is called as Sparse Matrix in C, if it contains more
number of zeros.
• The mathematical formula behind this C Sparse Matrix is:
T >= (m * n )/2 where T is total number of zeros.
• 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..
• Sparse Matrix Representations
Triplet Representation (Array Representation)
Linked Representation
7/4/2020 Megha Gupta KCS 301: DS Unit 1 102
Introduction to Array
Triplet Representation (Array Representation)
• In this representation, we consider only non-zero values along
with their row and column index values. In this representation,
the 0throw stores total number of rows, total number of columns
and the total number of non-zero values in the sparse matrix.
For example, consider a matrix of size 5 X 6 containing 6
number of non-zero values. This matrix can be represented as
shown in the image.
7/4/2020
Megha Gupta KCS 301: DS Unit 1
103
Introduction to Array
C Program that will convert 2D-representation to Sparse
representation.
#include <stdio.h>
void read_matrix(int a[10][10], int r,
int c);
void print_sparse(int b[20][3]);
void create_sparse(int a[10][10], int
r, int c, int b[20][3]);
void main() {
int a[10][10], b[20][3], r, c;
printf("nEnter the size of matrix
");
scanf("%d%d", &r, &c);
read_matrix(a, r, c);
create_sparse(a, r, c, b);
print_sparse(b);
}
void read_matrix(int a[10][10], int r, int c)
{
int i, j;
printf("nEnter elements of matrixn");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
printf("[%d][%d]: ", i, j);
scanf("%d", &a[i][j]);
}
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 104
Introduction to Array
void create_sparse(int a[10][10], int r, int c, int b[MAX][3]) {
int i, j, k=1;
b[0][0] = r; b[0][1] = c;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
if (a[i][j] != 0) {
b[k][0] = i;
b[k][1] = j;
b[k][2] = a[i][j];
k++;
}
}
b[0][2] = k - 1;
} }
void print_sparse(int b[MAX][3])
{
int i, c;
c = b[0][2];
printf("nSparse form - list of 3
triplesnn");
for (i = 0; i <= c; i++)
{
printf("%dt%dt%dn", b[i][0],
b[i][1], b[i][2]);
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 105
Introduction to Array
Linked 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
7/4/2020 Megha Gupta KCS 301: DS Unit 1 106
Introduction to Array
Algorithms
• Algorithm is a step-by-step procedure, which defines a set of
instructions to be executed in a certain order to get the desired
output.
• Algorithms are generally created independent of underlying
languages, i.e. an algorithm can be implemented in more than
one programming language.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 107
Introduction to Algorithms
Characteristics of an Algorithm
• Unambiguous − Algorithm should be clear and unambiguous. Each
of its steps (or phases), and their inputs/outputs should be clear
and must lead to only one meaning.
• Input − An algorithm should have 0 or more well-defined inputs.
• Output − An algorithm should have 1 or more well-defined
outputs, and should match the desired output.
• Finiteness − Algorithms must terminate after a finite number of
steps.
• Independent − An algorithm should have step-by-step directions,
which should be independent of any programming code
7/4/2020 Megha Gupta KCS 301: DS Unit 1 108
Introduction to Algorithms
Example:
An algorithm to sum N
natural numbers.
Sum(A[],n)
{
s=0;
for(i=1 to n) do
s=s+A[i]
return s
}
An algorithm to add to matrix
Matrixadd(A[][],B[][],C[][],m,n)
{
for(i=1 to n) do
for(j=1 to n) do
c[i][j]=a[i][j]+b[i][j]
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 109
Introduction to Algorithms
Algorithm for Insertion Sort
Insertion( A,n)
{
for(i=1 to n-1)
{
k=A[i]
j=i-1
while(j>0 && k< A[j])
{
A[j+1]= A[j]
j=j-1
}
A[j+1] = t
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1
110
Introduction to Algorithms
Performance analysis of an algorithm
• Space required to complete the task of that algorithm (Space
Complexity).
• Time required to complete the task of that algorithm (Time
Complexity)
7/4/2020 Megha Gupta KCS 301: DS Unit 1 111
Introduction to Algorithms
Space Complexity
When we design an algorithm to solve a problem, it needs some
computer memory to complete its execution. For any algorithm,
memory is required for the following purposes...
1. To store program instructions.
2. To store constant values.
3. To store variable values.
4. And for few other things like function calls, jumping statements
etc,.
Total amount of computer memory required by an algorithm to
complete its execution is called as space complexity of that algorithm
7/4/2020 Megha Gupta KCS 301: DS Unit 1 112
Introduction to Algorithms
Time Complexity
• Every algorithm requires some amount of computer time to
execute its instruction to perform the task. This computer time
required is called time complexity.
The time complexity of an algorithm can be defined as follows...
• The time complexity of an algorithm is the total amount of
time required by an algorithm to complete its execution.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 113
Introduction to Algorithms
Example 1
int sum(int a, int b)
{
return a+b;
}
Space Complexity –
In the above piece of code, it requires 2 bytes of memory to store
variable 'a' and another 2 bytes of memory is used for return value.
That means, totally it requires 4 bytes of memory to complete its
execution. And this 4 bytes of memory is fixed for any input value of 'a'.
This space complexity is said to be Constant Space Complexity.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 114
Introduction to Algorithms
Time Complexity –
• It requires 1 unit of time to calculate a+b and 1 unit of time to
return the value. That means, totally it takes 2 units of time to
complete its execution
• If any program requires a fixed amount of time for all input values
then its time complexity is said to be Constant Time Complexity.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 115
Introduction to Algorithms
Example 2
int sum(int A[ ], int n) {
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum; }
In the above piece of code it requires
'n*2' bytes of memory to store array variable 'a[ ]'
2 bytes of memory for integer parameter 'n'
4 bytes of memory for local integer variables 'sum' and 'i' (2 bytes each)
2 bytes of memory for return value.
That means, totally it requires '2n+8' bytes of memory to complete its execution.
Here, the total amount of memory required depends on the value of 'n'. As 'n'
value increases the space required also increases proportionately. This type of
space complexity is said to be Linear Space Complexity.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 116
Introduction to Algorithms
If the amount of time required by an algorithm is increased with the
increase of input value then that time complexity is said to be Linear
Time Complexity.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 117
Introduction to Algorithms
Time Space Tradeoff
7/4/2020 Megha Gupta KCS 301: DS Unit 1 118
Introduction to Algorithms
Asymptotic Notations
• Asymptotic analysis of an algorithm refers to defining the
mathematical boundation/framing of its run-time performance.
• Using asymptotic analysis, we can very well conclude the best case,
average case, and worst case scenario of an algorithm.
• Types of Asymptotic Notation
1. Big Oh(O)
2. Big Omega (Ω)
3. Theta (Θ)
4. Small Oh(o)
5. Small Omega (w)
7/4/2020 Megha Gupta KCS 301: DS Unit 1 119
Introduction to Algorithms
Purpose of Asymptotic Notations
1. To simplify the running time of the function
2. To describe the behavior of the function.
3. To provide asymptotic bound.
4. To describe how the running time of an algorithm increases
with increase in input size
7/4/2020 Megha Gupta KCS 301: DS Unit 1 120
Introduction to Algorithms
Big O Notation(O)
• It provide asymptotic upper bound (worst case running time ) to
a function.
O(g(n)) = { f(n): there exist positive constants c and n0 such that
0 <= f(n) <= c*g(n) for all n >= n0}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 121
Introduction to Algorithms
Q1 f(n) = 3n + 4, g(n) = n, Prove f(n) = O(g(n))
Sol.
To prove f(n) = O(g(n)) i.e. f(n) <= c.g(n)
It means 3n + 4 <=c.n
Let c= 5
n f(n) c.
g(n)
3n+4 5n
1 7 > 5
2 10 = 10
3 13 < 15
4 16 < 20
So, for n0 = 2
f(n) < = 5.g(n)
Hence f(n) = O(g(n))
7/4/2020 Megha Gupta KCS 301: DS Unit 1 122
Introduction to Algorithms
Big Omega Notation(Ω)
• This notation is known as the lower bound of the algorithm, or a
Best Case of an algorithm.
Ω (g(n)) = {f(n): there exist positive constants c and n0 such that
0 <= c*g(n) <= f(n) for all n >= n0}.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 123
Introduction to Algorithms
Theta Notation(Θ)
• The theta notation bounds a functions from above and below, so
it defines exact asymptotic behavior.
Θ(g(n)) = {f(n): there exist positive constants c1, c2 and n0
such that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 124
Introduction to Algorithms
Small o Notation(o)
• Small-o, commonly written as o, is an Asymptotic Notation to
denote the upper bound (that is not asymptotically tight) on the
growth rate of runtime of an algorithm.
o(g(n)) = { f(n): there exist positive constants c and n0 such that
0 <= f(n) < c*g(n) for all n >= n0}
• Another definition for o notation:
f(n) = o(g(n)) if and only if
lim(n→∞)f(n)/g(n)=0
7/4/2020 Megha Gupta KCS 301: DS Unit 1 125
Introduction to Algorithms
Small omega Notation(w)
• Small-omega, commonly written as w, is an Asymptotic Notation
to denote the lower bound (that is not asymptotically tight) on
the growth rate of runtime of an algorithm.
w(g(n)) = { f(n): there exist positive constants c and n0 such that
f(n) > c*g(n)>=0 for all n >= n0}
• Another definition for o notation:
f(n) = o(g(n)) if and only if
lim(n→∞)g(n)/f(n)=0
7/4/2020 Megha Gupta KCS 301: DS Unit 1 126
Introduction to Algorithms
Self Made Video Linked:
Youtube/other Video Links
• https://www.youtube.com/watch?v=zWg7U0OEAoE&list=PLBF3763AF2E1C572F&index=1
• https://www.youtube.com/watch?v=aGjL7YXI31Q&list=PLEbnTDJUr_IeHYw_sfBOJ6gk5pie0yP-0
• https://www.youtube.com/watch?v=FEnwM-iDb2g&list=PLEbnTDJUr_IeHYw_sfBOJ6gk5pie0yP-0&index=2
• https://www.youtube.com/watch?v=HEjmH9wKiMo&list=PLEbnTDJUr_IeHYw_sfBOJ6gk5pie0yP-0&index=6
• https://www.youtube.com/watch?v=sr_bR1WwcLY
• https://www.youtube.com/watch?v=puMz5Jt96sg
• https://www.youtube.com/watch?v=d_XvFOkQz5k&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=1
• https://www.youtube.com/watch?v=KELqVT7hjeE&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=2
• https://www.youtube.com/watch?v=CZYR2v8rYLA&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=3
• https://www.youtube.com/watch?v=-lY4_THb2wM&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=4
7/4/2020 Megha Gupta KCS 301: DS Unit 1 127
Faculty Video Links, Youtube & NPTEL
Video Links and Online Courses Details
Q.1 What is a data structure?
Q.2 What does abstract data type means?
Q.3 Explain about the types of linked lists
Q.4 Write an algorithm to merge two sorted arrays into a third array.
Do not sort the third array.
Q.5 What data structure would you mostly likely see in a non recursive
implementation of a recursive algorithm?
Q.6 List out the areas in which data structures are applied extensively?
Q.7 A two-dimensional array TABLE [6] [8] is stored in row major order
with base address 351. What is the address of TABLE [3] [4]?
Q.8 How do you find the complexity of an algorithm? What is the
relation between the time and space complexities of an algorithm?
Justify your answer with an example.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 128
Daily Quiz
Question 1: Print Elements of a Matrix in Spiral Order Write a program that
reads an MxN matrix A and prints its elements in spiral order. You should start
from the element in the 0th row and 0th column in the matrix and proceed in a
spiral order as shown below.
Output for the above matrix: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Question 2: Write a program that reads an NxN square matrix M that
calculates the sum of the elements in individual rows, individual columns and
the two main diagonals. Among these sums, print the largest.
Consider the following matrix of order 3x3:
1 10 13
2 14 12
3 9 8
The row sum values are 1+10+13=24, 2+14+12=28 and 3+9+8=20. The
column sum values are 1+2+3=6, 10+14+9=33 and 13+12+8=33. The
diagonal sums are 1+14+8=23 and 13+14+3=30. The expected output is
maximum among these sums, which is 33.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 129
Weekly Assignment
Question 1: Print Elements of a Matrix in Spiral Order Write a program that
reads an MxN matrix A and prints its elements in spiral order. You should start
from the element in the 0th row and 0th column in the matrix and proceed in a
spiral order as shown below.
Output for the above matrix: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Question 2: Write a program that reads an NxN square matrix M that
calculates the sum of the elements in individual rows, individual columns and
the two main diagonals. Among these sums, print the largest.
Consider the following matrix of order 3x3:
1 10 13
2 14 12
3 9 8
The row sum values are 1+10+13=24, 2+14+12=28 and 3+9+8=20. The
column sum values are 1+2+3=6, 10+14+9=33 and 13+12+8=33. The
diagonal sums are 1+14+8=23 and 13+14+3=30. The expected output is
maximum among these sums, which is 33.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 130
Weekly Assignment
7/4/2020 Megha Gupta KCS 301: DS Unit 1 131
Weekly Assignment
Question 3: Write a program in C to count a total number of duplicate elements in an array.
Test Data :
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 5
element - 1 : 1
element - 2 : 1
Expected Output :
Total number of duplicate elements found in the array is : 1
Question 4.Write a program in C to merge two arrays of same size sorted in decending order.
Test Data :
Input the number of elements to be stored in the first array :3
Input 3 elements in the array :
element - 0 : 1
element - 1 : 2
element - 2 : 3
Input the number of elements to be stored in the second array :3
Input 3 elements in the array :
element - 0 : 1
element - 1 : 2
element - 2 : 3
1. In ........, search start at the beginning of the list and check every element in the list.
a. Binary search
b. Hash Search
c. Linear search
d. Binary Tree search.
2. To represent hierarchical relationship between elements, which data structure is suitable?
a. Graph
b. Tree
c. Dequeue
d. Priority Queue
3. Which of the following data structure is linear type?
a. Stack
b. Graph
c. Trees
d. Binary tree
4.Which of the following data structure can’t store the nonhomogeneous data elements?
a. Arrays
b. Stacks
c. Records
d. None of the above
7/4/2020 Megha Gupta KCS 301: DS Unit 1 132
MCQ s
7/4/2020 Megha Gupta KCS 301: DS Unit 1 133
MCQ s
5. Two main measures for the efficiency of an algorithm are
a. Processor and memory
b. Complexity and capacity
c. Time and space
d. Data and space
6. The Worst case occur in linear search algorithm when
a. Item is somewhere in the middle of the array
b. Item is not in the array at all
c. Item is the last element in the array
d. Item is the last element in the array or is not there at all
7. The complexity of Binary search algorithm is
a. O(n)
b. O(log )
c. O(n2)
d. O(n log n)
8. The complexity of linear search algorithm is
a. O(n)
b. O(log n)
c. O(n2)
d. O(n log n)
7/4/2020 Megha Gupta KCS 301: DS Unit 1 134
MCQ s
9. Arrays are best data structures
a. for relatively permanent collections of data
b. for the size of the structure and the data in the structure are constantly changing
c. for both of above situation
d. for none of above situation
10. Linked lists are best suited
a. for relatively permanent collections of data
b. for the size of the structure and the data in the structure are constantly changing
c. for both of above situation
d. for none of above situation
• https://drive.google.com/open?id=159ihlpBttJRK9pgu9OVIyCGJ8AC
fsZ1y
7/4/2020 Megha Gupta KCS 301: DS Unit 1 135
Old Question Papers
7/4/2020 Megha Gupta KCS 301: DS Unit 1 136
Expected Questions for University Exam
Q1. Assume the declaration of multi-dimensional arrays A and B to be,
A (-2:2, 2:22) and B (1:8, -5:5, -10:5)
(i) Find the length of each dimension and number of elements in A and B.
(ii) Find the address of element B (2, 2, 3), assuming Base address of B = 400
and there are W=4 words per memory location.
Q2. Write a program to insert a new element in the given unsorted array at kth
position.
Q3. Define data structure? What are the factors that influence the choice of particular
data structure?
Q4 . A 2 dimensional array DATA [-100:100,-5:50] is stored row major order with base
address 10. Calculate the address of DATA [99][49].
Q5 Explain Binary search and its limitations.
Q6 Write the difference between Linked list and array.
Introduction to List and LinkedLists
• List is a term used to refer to a linear collection of data items. A
List can be implemented either by using arrays or linked lists.
• Usually, a large block of memory is occupied by an array which
may not be in use and it is difficult to increase the size of an
array.
• Another way of storing a list is to have each element in a list
contain a field called a Linked or pointer, which contains the
address of the next element in the list.
• The successive elements in the list need not occupy adjacent
space in memory. This type of data structure is called a
linked list.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 137
Introduction to Linked List
What are Linked Lists
A linked list is a lineardata structure.
Nodes make up linkedlists.
Nodes are structures made up of data and
a pointer to another node.
Usually the pointer iscalled next.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 138
Introduction to Linked List
Linked List
• It is the most commonly used data structure used to store similar
type of data in memory.
• The elements of a linked list are not stored in adjacent
memory locations as in arrays.
• It is a linear collection of data elements, called nodes, where
the linear order is implemented by means of pointers.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 139
Introduction to Linked List
Linked List
• In a linear or single-linked list, a node is connected to the next
node by a single Linked.
• A node in this type of linked list contains two types of fields
• data: which holds a list element
• next: which stores a Linked (i.e. pointer) to the next node in the
list.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 140
Introduction to Linked List
Linked List
• The structure defined for a single linked list is implemented as
follows:
struct Node{
int info;
structNode * next;
}
• The structure declared for linear linked list holds two members
• An integer type variable ‘data’ which holds the elements and
• Another type ‘node’, which has next, which stores the
address of the next node in the list.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 141
Introduction to Linked List
Figurative Representation
7/4/2020 Megha Gupta KCS 301: DS Unit 1 142
Introduction to Linked List
Properties of Linked list
• The nodes in a linked list are not stored contiguously in the
memory
• You don’t have to shift any element in the list
• Memory for each node can be allocated dynamically whenever
the need arises.
• The size of a linked list can grow or shrink dynamically
7/4/2020 Megha Gupta KCS 301: DS Unit 1 143
Introduction to Linked List
Operations on Linked List
• Creation:
• This operation is used to create a linked list
• Insertion / Deletion:
• At/From the beginning of the linked list
• At/From the end of the linked list
• At/From the specified position in a linked list
• Traversing:
• Traversing may be either forward or backward
• Searching:
• Finding an element in a linked list
• Concatenation:
• The process of appending second list to the end of the first list
7/4/2020 Megha Gupta KCS 301: DS Unit 1 144
Introduction to Linked List
Arrays Vs Linked Lists
Arrays Linked list
Fixed size: Resizing is expensive Dynamic size
Insertions and Deletions are
inefficient:
Elements are usually shifted
Insertions and Deletions are efficient:
No shifting
Random access i.e., efficient indexing No random access
Not suitable for operations
requiring accessing elements by
index such as sorting
No memory waste if the array is full
or almost full; otherwise may result
in much memory waste.
Since memory is allocated
dynamically(acc. to our need)
there is no waste of memory.
Sequential access is faster [Reason:
Elements in contiguous memory
locations]
Sequential access is slow [Reason:
Elements not in contiguous
memory locations]
7/4/2020 Megha Gupta KCS 301: DS Unit 1 145
Linked List
Types of Linked List
• Singly Linked List
• Doubly linked list
• Circular linked list
• Circular doubly linked list
7/4/2020 Megha Gupta KCS 301: DS Unit 1 146
Introduction to Linked List
Singly Linked List
• A singly linked list is a dynamic data structure which may grow
or shrink, and growing and shrinking depends on the operation
made.
• In this type of linked list each node contains two fields one is data
field which is used to store the data items and another is next
field that is used to point the next node in the list.
5 3 8 null
next next nextinfo info info
7/4/2020 Megha Gupta KCS 301: DS Unit 1 147
Introduction to Linked List
Creating a Linked List
• The head pointer is used to create and access unnamed nodes.
struct Node{
int info;
struct Node* next;
};
typedef struct
Node NodeType;
NodeType* head;
head=(NodeType *) malloc (sizeof( NodeType ) );
• The above statement obtains memory to store a node and
assigns its address to head which is a pointer variable.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 148
Introduction to Linked List
Creating a Node
• Tocreate a new node, we use the malloc function to
dynamically allocate memory for the new node.
• After creating the node, we can store the new item in the node
using a pointer to that node.
• Note that p is not a node; instead it is a pointer to a
node.
Nodetype *p;
p=(NodeType *) malloc
(sizeof( NodeType ) ); p-
>info=50;
p->next = NULL;
7/4/2020 Megha Gupta KCS 301: DS Unit 1 149
Introduction to Linked List
Creating an empty list
void createEmptyList(NodeType *head)
{
head=NULL;
}
OR SIMPLY
NodeType *head =Null;
7/4/2020 Megha Gupta KCS 301: DS Unit 1 150
Introduction to Linked List
Inserting an Element
• While inserting an element or a node in a linked list, we have
to do following things:
• Allocate a node
• Assign a data to info field of the node.
• Adjust a pointer
• We can insert an element in following places
• At the beginning of the linked list
• At the end of the linked list
• At the specified position in a linked list
7/4/2020 Megha Gupta KCS 301: DS Unit 1 151
Introduction to Linked List
An algorithm to insert a node at the beginning of the singly
linked list
Let *head be the pointer to first node in the current list
1. Create a new node using mallocfunction
NewNode=(NodeType*)malloc(sizeof(Node
Type));
2. Assign data to the info field of newnode
NewNode->info=newItem;
3. Set next of new node tohead
NewNode->next=head;
4. Set the head pointer to the newnode
head=NewNode;
5. End
7/4/2020 Megha Gupta KCS 301: DS Unit 1 152
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 153
Introduction to Linked List
Insert A Node At The Beginning Of The Singly Linked List
Inserting a node at the beginning of the singly linkedlist
7/4/2020 Megha Gupta KCS 301: DS Unit 1 154
Introduction to Linked List
An algorithm to insert a node at the end of the singly linked
list
let *head be the pointer to first node in the current list
1. Create a new node using mallocfunction
NewNode=(NodeType*)malloc(sizeof(NodeType));
2. Assign data to the info field of newnode
NewNode->info=newItem;
3. Set next of new node toNULL
NewNode->next=NULL;
4. if (head ==NULL) then
Set head =NewNode.and exit.
5. Set temp=head;
6. while(temp->next!=NULL)
temp=temp->next; //increment temp
7. Set temp->next=NewNode;
8. End
7/4/2020 Megha Gupta KCS 301: DS Unit 1 155
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 156
An algorithm to insert a node at the end of the singly linked
list
Introduction to Linked List
An algorithm to insert a node after the given node in singly
linked list
let *head be the pointer to first node in the current list and *p be the
pointer to the node after which we want to insert a new node.
1. Create a new node using mallocfunction
NewNode=(NodeType*)malloc(sizeof(NodeType));
2. Assign data to the info field of newnode
NewNode->info=newItem;
3. Set next of new node to next ofp
NewNode->next=p->next;
4. Set next of p to NewNode
p->next =NewNode
5. End
7/4/2020 Megha Gupta KCS 301: DS Unit 1 157
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 158
Introduction to Linked List
An algorithm to insert a node at the specified position in a
linked list
let *head be the pointer to first node in the current list
1. Create a new node using mallocfunction
NewNode=(NodeType*)malloc(sizeof(NodeType));
2. Assign data to the info field of new node
NewNode->info=newItem;
3. Enter position of a node at which you want to insert a new node.
Let this position is pos.
4. Set temp=head;
5. if (head ==NULL)then
printf(“void insertion”); and exit(1).
6. for(i=1; i<pos; i++)
temp=temp->next;
7. Set NewNode->next=temp->next;
set temp->next =NewNode..
8. End
7/4/2020 Megha Gupta KCS 301: DS Unit 1 159
Introduction to Linked List
Deleting Nodes
• A node may be deleted:
• From the beginning of the linked
list
• From the end of the linked list
• From the specified position in a
linked list
7/4/2020 Megha Gupta KCS 301: DS Unit 1 160
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 161
Deleting Nodes
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 162
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 163
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 164
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 165
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 166
Introduction to Linked List
Searching an item in a linkedlist
• Let *head be the pointer to first node in the current
list
1. If head==Null
Print “Empty List”
2. Else, enter an item to be searched askey
3. Set temp==head
4. While temp!=Null
If (temp->info == key)
Print “search success”
temp=temp->next;
5. If temp==Null
Print “Unsuccessful search”
7/4/2020 Megha Gupta KCS 301: DS Unit 1 167
Introduction to Linked List
7/4/2020 Megha Gupta KCS 301: DS Unit 1 168
Introduction to Linked List
What is circular linked list?
• Circular linked list is a variation of linked list in which the first
elements points to the next element and the last element
points to the first element.
• Both singly and doubly linked list can be made into a circular
linked list.
• Circular linked list can be used to help traverse the same list
again and again if needed.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 169
Circular Linked List
Fun fact:
If you are worried about its implementation, then stop doing
that because instead of placing NULL at the last node’s address
field you are placing the address of very first node!
7/4/2020 Megha Gupta KCS 301: DS Unit 1 170
Circular Linked List
Circular linked list vs. Linear linked list
• A circularly linked list may be a natural option to represent arrays
that are naturally circular, e.g. the corners of a polygon, a pool
of buffers that are used and released in FIFO order, or a set of processes
that should be time-shared. In these applications, a pointer to any node
serves as a handle to the whole list.
• With a circular list, a pointer to the last node gives easy access also to
the first node, by following one Linked. Thus, in applications that
require access to both ends of the list, a circular structure allows one to
handle the structure by a single pointer, instead of two.
• The simplest representation for an empty circular list (when such a
thing makes sense) is a null pointer, indicating that the list has no
nodes. Without this choice, many algorithms have to test for this
special case, and handle it separately. By contrast, the use of null to
denote an empty linear list is more natural and often creates fewer
special cases.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 171
Circular Linked List
Types of circular linked list
1. Singly: The last node points to the first node and there is only
Linked between the nodes of linked list.
2. Doubly: The last node points to the first node and there are
two links between the nodes of linked list.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 172
Circular Linked List
Advantages of Circular linked lists
1. Any node can be a starting point. We can traverse the whole list
by starting from any point. We just need to stop when the first
visited node is visited again.
2. Circular lists are useful in applications to repeatedly go around
the list. For example: when multiple applications are running on
a PC, it is common for the operating system to put the running
applications on a list and then to cycle through them, giving each
of them a slice of time to execute, and then making them wait
while the CPU is given to another application. It is convenient for
the operating system to use a circular list so that when it reaches
the end of the list it can cycle around to the front of the list.
3. Circular Doubly Linked Lists are used for implementation of
advanced data structures like Fibonacci Heap.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 173
Circular Linked List
Disadvantages of Circular linked list
1. Depending on the implementation, inserting at start of list would
require doing a search for last node which could be expensive.
2. Finding end of the list and loop control is harder ( no NULL’s to
mark the beginning and end).
7/4/2020 Megha Gupta KCS 301: DS Unit 1 174
Circular Linked List
Operations on singly circular linked list
• Insertion
• Deletion
• Display
7/4/2020 Megha Gupta KCS 301: DS Unit 1 175
Circular Linked List
Insertion
• Insertion can be of three types.
▫ Insert at first
▫ Insert at last
▫ Insert after constant
• Note: insertion after constant in circular and linear linked list
is exact same .
7/4/2020 Megha Gupta KCS 301: DS Unit 1 176
Circular Linked List
Insertion at first
7/4/2020 Megha Gupta KCS 301: DS Unit 1 177
Circular Linked List
Algorithm
• Start.
• Declare struct node *t.
• Set t:=start.
• Create a new node n by
malloc function and enter
the information in info part.
• Check if start=NULL set
start=n
set start->next=start. else
• Set n->next=start.
Program
void addfront()
{
struct node *t=start;
struct node *n=(struct
node*)malloc(sizeof(struct
node));
printf(“nenter the
information”); scanf(“%d”,&n-
>info);
7/4/2020 Megha Gupta KCS 301: DS Unit 1 178
Circular Linked List
Algorithm
• Repeat step(a)
while(t->next!=start)
▫ (a) set t:=t->next.
• [end of loop]
• Set t->next=n.
• Set start=n. [end if]
• Stop.
Program
if(start==NULL)
{
start=n;
start->next=start;
}
else
{
n->next=start; while(t-
>next!=start) t=t->next;
t->next=n;
start=n;
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 179
Circular Linked List
Insert at last
7/4/2020 Megha Gupta KCS 301: DS Unit 1 180
Circular Linked List
Algorithm
• Start.
• Declare struct node *t.
• Set t:=start.
• Create a new node n by
malloc function and enter
the information in info part.
• Check if start=NULL then,
set start:=n.
set start->next:=start.
Otherwise
• Set n->next:=start.
Program
void addlast()
{
struct node *t=start;
struct node *n=(struct
node*)malloc(sizeof(struct
node));
printf(“nenter the
information”); scanf(“%d”,&n-
>info);
7/4/2020 Megha Gupta KCS 301: DS Unit 1 181
Circular Linked List
Algorithm
• Repeat step(a)
while(t!=NULL)
▫ (a) set t:=t->next.
• [end of loop]
• Set t->next=n. [end
if]
• Stop.
Program
if(start==NULL)
{
start=n;
start->next=start;
}
else
{
n->next=start;
while(t!=NULL) t=t-
>next;
t->next=n;
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 182
Circular Linked List
Deletion :
• Deletion can be of three types.
▫ Delete from front
▫ Delete from last
▫ Deletion from mid
• Note: deletion from mid in circular and linear linked list is exact
same .
7/4/2020 Megha Gupta KCS 301: DS Unit 1 183
Circular Linked List
Delete from front
7/4/2020 Megha Gupta KCS 301: DS Unit 1 184
Circular Linked List
Algorithm
start.
Check if (start=NULL) then,
print “empty list”
Check if
(start->next=start) then,
declare free (t)
set start:=NULL
otherwise
Repeat step(a) while(t-
>next!=start)
▫ (a) set t:=t->next
[end of loop]
void delfront()
{
struct node *t=start; if
(start==NULL)
printf (“nempty list”); else if
(start->next==start)
{
free (t);
start=NULL;
}
else
{
while(t->next!=start){
t=t->next;
Program
7/4/2020 Megha Gupta KCS 301: DS Unit 1 185
Circular Linked List
set start:=start->next
Declare free(t->next).
Set t->next:=start.
[end of if]
stop
start=start->next;
free(t->next);
t->next=start;
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 186
Circular Linked List
Continue…
Delete from last
7/4/2020 Megha Gupta KCS 301: DS Unit 1 187
Circular Linked List
Algorithm
• start.
• Check if (start=NULL) then,
print “empty list”
• Check if (start->next=start)
then,
declare free (t)
set start:=NULL
otherwise
• Repeat step(a)
while(t->next->next!=start)
▫ (a) set t:=t->next
• [end of loop]
• Declare free(t->next).
• Set t->next:=start.
• [end if]
• stop
Program
void dellast()
{
struct node *t=start;
if (start==NULL)
printf(“nempty list”);
else if (start->next==start)
{
free (t);
start=NULL ;
}
else
{
while(t->next->next!=start)
t=t->next;
free(t->next);
t->next=start;
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 188
Circular Linked List
Display
7/4/2020 Megha Gupta KCS 301: DS Unit 1 189
Circular Linked List
Algorithm Program
• start.
• Set struct node
*t:=start.
• Check if(start=NULL) then,
print “empty list” otherwise
• Repeat step a and b
while(t->next!=start)
▫ (a) print t->info
▫ (b) set t:=t->next
• [end of loop]
• Print t->info [end if]
• stop
Void display()
{
struct node *t=start;
if(start=NULL)
printf (“nempty list”);
else
{
while(t->next!=start)
{
printf(“%d”, t->info);
t=t->next;
}
printf(“%d”, t->info);
}
}
7/4/2020 Megha Gupta KCS 301: DS Unit 1 190
Circular Linked List
APPLICATIONS OF LINKED LIST
1.Applications that havean MRU list (a linked list of file names)
2. The cache in your browser that allows you to hit the BACK button (a
linked list ofURLs)
3. Undo functionality in Photoshopor Word (a linked list of state)
4. A stack, hash table, and binary tree can be implemented using a
doubly linkedlist.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 191
Linked List
Doubly Linked List
Doubly linked list is a type of linked list in which each node apart from
storing its data has two links. The first Linked points to the previous
node in the list and the second Linked points to the next node in the
list. The first node of the list has its previous Linked pointing to NULL
similarly the last node of the list has its next node pointing to NULL.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 192
Linked List
The two links help us to traverse the list in both backward and forward
direction. But storing an extra Linked requires some extra space.
First we define the node.
struct node
{
int data; // Data
node *prev; // A reference to the previous node
node *next; // A reference to the next node
};
7/4/2020 Megha Gupta KCS 301: DS Unit 1 193
Linked List
Important Points to be Remembered In double linked list, the first
node must be always pointed by head. Always the previous field of the
first node must be NULL. Always the next field of the last node must be
NULL
7/4/2020 Megha Gupta KCS 301: DS Unit 1 194
Linked List
Operations on Double Linked List
In a double linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
7/4/2020 Megha Gupta KCS 301: DS Unit 1 195
Linked List
Insertion
In a double linked list, the insertion operation can be performed in
three ways as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
7/4/2020 Megha Gupta KCS 301: DS Unit 1 196
Linked List
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of
the double linked list...
• Step 1 - Create a newNode with given value and newNode →
previous as NULL.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, assign NULL to newNode → next and
newNode to head.
• Step 4 - If it is not Empty then, assign head to newNode → next and
newNode to head.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 197
Linked List
Inserting At End of the list
We can use the following steps to insert a new node at end of the
double linked list...
• Step 1 - Create a newNode with given value and newNode → next as
NULL.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty, then assign NULL to newNode → previous and
newNode to head.
• Step 4 - If it is not Empty, then, define a node pointer temp and
initialize with head.
• Step 5 - Keep moving the temp to its next node until it reaches to the
last node in the list (until temp → next is equal to NULL).
• Step 6 - Assign newNode to temp → next and temp to newNode →
previous.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 198
Linked List
Inserting At Specific location in the list (After a Node)
We can use the following steps to insert a new node after a node in the double
linked list...
• Step 1 - Create a newNode with given value.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, assign NULL to both newNode → previous &
newNode → next and set newNode to head.
• Step 4 - If it is not Empty then, define two node pointers temp1 & temp2 and
initialize temp1 with head.
• Step 5 - Keep moving the temp1 to its next node until it reaches to the node
after which we want to insert the newNode (until temp1 → data is equal to
location, here location is the node value after which we want to insert the
newNode).
• Step 6 - Every time check whether temp1 is reached to the last node. If it is
reached to the last node then display 'Given node is not found in the list!!!
Insertion not possible!!!' and terminate the function. Otherwise move the
temp1 to next node.
• Step 7 - Assign temp1 → next to temp2, newNode to temp1 → next, temp1
to newNode → previous, temp2 to newNode → next and newNode to temp2
→ previous.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 199
Linked List
Deletion
In a double linked list, the deletion operation can be performed in
three ways as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
7/4/2020 Megha Gupta KCS 301: DS Unit 1 200
Linked List
Deleting from Beginning of the list
We can use the following steps to delete a node from beginning of the
double linked list...
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
• Step 3 - If it is not Empty then, define a Node pointer 'temp' and
initialize with head.
• Step 4 - Check whether list is having only one node (temp →
previous is equal to temp → next)
• Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting
Empty list conditions)
• Step 6 - If it is FALSE, then assign temp → next to head, NULL to
head → previous and delete temp.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 201
Linked List
Deleting from End of the list
We can use the following steps to delete a node from end of the
double linked list...
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not
possible' and terminate the function.
• Step 3 - If it is not Empty then, define a Node pointer 'temp' and
initialize with head.
• Step 4 - Check whether list has only one Node (temp → previous and
temp → next both are NULL)
• Step 5 - If it is TRUE, then assign NULL to head and delete temp. And
terminate from the function. (Setting Empty list condition)
• Step 6 - If it is FALSE, then keep moving temp until it reaches to the
last node in the list. (until temp → next is equal to NULL)
• Step 7 - Assign NULL to temp → previous → next and delete temp.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 202
Linked List
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the
double linked list...
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
• Step 3 - If it is not Empty, then define a Node pointer 'temp' and
initialize with head.
• Step 4 - Keep moving the temp until it reaches to the exact node to
be deleted or to the last node.
• Step 5 - If it is reached to the last node, then display 'Given node not
found in the list! Deletion not possible!!!' and terminate the fuction.
• Step 6 - If it is reached to the exact node which we want to delete,
then check whether list is having only one node or not
7/4/2020 Megha Gupta KCS 301: DS Unit 1 203
Linked List
Step 7 - If list has only one node and that is the node which is to be
deleted then set head to NULL and delete temp (free(temp)).
• Step 8 - If list contains multiple nodes, then check whether temp is
the first node in the list (temp == head).
• Step 9 - If temp is the first node, then move the head to the next
node (head = head → next), set head of previous to NULL (head →
previous = NULL) and delete temp.
• Step 10 - If temp is not the first node, then check whether it is the
last node in the list (temp → next == NULL).
• Step 11 - If temp is the last node then set temp of previous of next
to NULL (temp → previous → next = NULL) and delete temp
(free(temp)).
• Step 12 - If temp is not the first node and not the last node, then set
temp of previous of next to temp of next (temp → previous → next =
temp → next), temp of next of previous to temp of previous (temp →
next → previous = temp → previous) and delete temp (free(temp)).
7/4/2020 Megha Gupta KCS 301: DS Unit 1 204
Linked List
Displaying a Double Linked List
We can use the following steps to display the elements of a double
linked list...
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate
the function.
• Step 3 - If it is not Empty, then define a Node pointer 'temp' and
initialize with head.
• Step 4 - Display 'NULL <--- '.
• Step 5 - Keep displaying temp → data with an arrow (<===>) until
temp reaches to the last node
• Step 6 - Finally, display temp → data with arrow pointing to NULL
(temp → data ---> NULL).
7/4/2020 Megha Gupta KCS 301: DS Unit 1 205
Linked List
• Polynomials
6 2 3 8
0 2
Index
represents
exponents
-3 18 0 0 23
0 42
•Array Implementation:
• p1(x) = 8x3 + 3x2 + 2x + 6
• p2(x) = 23x4 + 18x -3
p1(x) p2(x)
7/4/2020 Megha Gupta KCS 301: DS Unit 1 206
Linked List
•This is whyarrays aren’tgood to represent polynomials:
• p3(x) = 16x21 - 3x5 + 2x +6
6 2 0 0 -3 0 ………… 0 16
WASTE OF SPACE!
7/4/2020 Megha Gupta KCS 301: DS Unit 1 207
Linked List
•Advantages of using anArray:
• only good for non-sparsepolynomials.
• ease of storage andretrieval.
•Disadvantages of using anArray:
• havetoallocate arraysize ahead of time.
• huge array size required for sparse polynomials. Waste of
space andruntime.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 208
Linked List
• Polynomial Representation
• Linked list Implementation:
• p1(x) = 23x9 + 18x7 + 41x6 + 163x4 + 3
• p2(x) = 4x6 + 10x4 + 12x + 8
23 9 18 7 41 6 18 7 3 0
4 6 10 4 12 1 8 0
P1
P2
NODE (contains coefficient &exponent)
TAIL (contains pointer)
7/4/2020
Megha Gupta KCS 301: DS Unit 1
209
Linked List
•Advantages of using a Linkedlist:
savespace (don’t have toworryaboutsparse polynomials) and easy to
maintain
don’t need toallocate list size and can declare nodes (terms) only as
needed
•Disadvantages of using a Linked list :
can’t go backwards through thelist
can’t jump to the beginning of the listfrom theend.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 210
Linked List
Polynomials
A(x)
em 1
am 1x am
em 2 e0
2 x ... a0 x
Representation
struct polynode {
int coef;
int exp;
struct polynode * next;
};
typedef struct polynode *polyptr;
coef exp next
7/4/2020 Megha Gupta KCS 301: DS Unit 1 211
Linked List
Adding polynomials using a Linkedlist
representation: (storing the result inp3)
Todo this, we haveto break the process down to cases:
• Case 1: exponent of p1 > exponent ofp2
Copy node of p1 to end ofp3. [go to nextnode]
• Case 2: exponent of p1 < exponent ofp2
Copy node of p2 to end ofp3. [go to nextnode]
• Case 3: exponent of p1 = exponent ofp2
Create a new node in p3 with the same exponent and with the sum of
the coefficients of p1 andp2.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 212
Linked List
Example
3 14 2 8
a
8 14 -3 10
b
b
1 0 null
10 6 null
8x14
3x10
10x 6
a 3x14
2x8
1
7/4/2020 Megha Gupta KCS 301: DS Unit 1 213
Linked List
Adding Polynomials
3 14
a
8 14
2 8
-3 10
1 0
10 6
b
11 14
d
a->expon == b->expon
3 14 1 0
a
2 8
-3 10 10 6
b
8 14
11 14 -3 10 a->expon < b->expon
7/4/2020 Megha Gupta KCS 301: DS Unit 1 214
Linked List
3 14 2 8 1 0
a
8 14 -3 10 10 6
b
11 14 -3 10
d
a->expon > b->expon
2 8
7/4/2020 Megha Gupta KCS 301: DS Unit 1 215
Linked List
Q1. What is the output of following function for start pointing to first node of
following linked list? 1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
Q2. What type of memory allocation is referred for Linked lists?
7/4/2020 Megha Gupta KCS 301: DS Unit 1 216
Daily Quiz
Q3. Describe what is Node in Linked list? And name the types of Linked Lists?
Q4. Mention what is the difference between Linear Array and Linked List?
Q5. Mention what are the applications of Linked Lists?
Q6. What does the dummy header in linked list contain?
Q7. Mention what is the difference between singly and doubly linked lists?
Q8. Mention what is the biggest advantage of linked lists?
Q9. Mention how to insert a new node in linked list where free node will be
available?
7/4/2020 Megha Gupta KCS 301: DS Unit 1 217
Daily Quiz
7/4/2020 Megha Gupta KCS 301: DS Unit 1 218
Weekly Assignment
Q1. Assume that the structure of a Linked List node is as follows:
struct node {
int data;
struct node *next;
}; What does the following function print for a given Linked List which
has elements in the order 1->2->3->4->5->6. Explain your answer.
1. void fun(struct node* head){
2. if(head == NULL)
3. return;
4. printf("%d ", head->data);
5. if(head->next != NULL )
6. fun(head->next->next);
7. printf("%d ", head->data);
8. }
7/4/2020 Megha Gupta KCS 301: DS Unit 1 219
Weekly Assignment
Q2. Write a C Program to reverse the Linked list
Q3. Write a C Program to merge two Linked list.
Q4. Write a C Program to alternate print the content of the list.
Q5. Write a program for printing the following in a given linked list:
a. Maximum
b. Minimum
7/4/2020 Megha Gupta KCS 301: DS Unit 1 220
Weekly Assignment
Q6. Print the sum of all even numbers stored in a circular linked list.
Q7. Take N numbers as input from the user and create a doubly linked
list.
Q 8. Find the smallest number in the doubly linked list.
Q 9. Delete the smallest number in the doubly linked list.
Q 10. Write the C Program to add all even number in the list.
1. What does the following function do for a given Linked List with first
node as head?
void fun1(struct node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
A Prints all nodes of linked lists
B Prints all nodes of linked list in reverse order
C Prints alternate nodes of Linked List
D Prints alternate nodes in reverse order
7/4/2020 Megha Gupta KCS 301: DS Unit 1 221
MCQ s
2. Which of the following points is/are true about Linked List data
structure when it is compared with array
A Arrays have better cache locality that can make them better in terms
of performance.
B It is easy to insert and delete elements in Linked List
C Random access is not allowed in a typical implementation of Linked
Lists
D The size of array has to be pre-decided, linked lists can change their
size any time.
E All of the above
7/4/2020 Megha Gupta KCS 301: DS Unit 1 222
MCQ s
7/4/2020 Megha Gupta KCS 301: DS Unit 1 223
MCQ s
3. Which of the following sorting algorithms can be used to sort a
random linked list with minimum time complexity?
A Insertion Sort
B Quick Sort
C Heap Sort
D Merge Sort
4. In the worst case, the number of comparisons needed to search a
singly linked list of length n for a given element is (GATE CS 2002)
A log 2 n
B n/2
C log 2 n – 1
D n
7/4/2020 Megha Gupta KCS 301: DS Unit 1 224
MCQ s
5. Is it possible to create a doubly linked list using only one pointer with
every node.
A Not Possible
B Yes, possible by storing XOR of addresses of previous and next nodes.
C Yes, possible by storing XOR of current node and next node
D Yes, possible by storing XOR of current node and previous node
6. You are given pointers to first and last nodes of a singly linked list,
which of the following operations are dependent on the length of the
linked list?
A Delete the first element
B Insert a new element as a first element
C Delete the last element of the list
D Add a new element at the end of the list
7/4/2020 Megha Gupta KCS 301: DS Unit 1 225
MCQ s
7. Consider the following function to traverse a linked list.
void traverse(struct Node *head) {
while (head->next != NULL)
{
printf("%d ", head->data);
head = head->next;
}
}
Which of the following is FALSE about above function?
A The function may crash when the linked list is empty
B The function doesn't print the last node when the linked list is not
empty
C The function is implemented incorrectly because it changes head
7/4/2020 Megha Gupta KCS 301: DS Unit 1 226
MCQ s
8. Let P be a singly linked list. Let Q be the pointer to an intermediate
node x in the list. What is the worst-case time complexity of the best
known algorithm to delete the node x from the list?
A O(n) B O(log2 n)
C O(logn) D O(1)
9. The concatenation of two lists is to be performed in O(1) time. Which
of the following implementations of a list should be used?
A singly linked list
B doubly linked list
C circular doubly linked list
D array implementation of lists
10. In a doubly linked list, the number of pointers affected for an
insertion operation will be
A 4 B 0 C 1 D None of these
7/4/2020 Megha Gupta KCS 301: DS Unit 1 227
Expected Questions for University Exam
Q1. Write a program in c to delete a specific element in single linked list.
Double linked list takes more space than single linked list for storing one extra
address. Under what condition, could a double linked list more beneficial than
single linked list.
Q2. What is a doubly linked list? How is it different from the single linked list?
Q3. What are the advantages and disadvantages of array over linked list?
Q4 . Write a program to implement linear linked list, showing all the
operations that
can be performed on a linked list.
Q5. Implement Doubly Circular Linked list and insert an element at a given
position in the doubly circular Linked list.
https://drive.google.com/open?id=15fAkaWQ5c
cZRZPzwlP4PBh1LxcPp4VAd
7/4/2020 Megha Gupta KCS 301: DS Unit 1 228
Old Question Papers
7/4/2020 Megha Gupta KCS 301: DS Unit 1 229
Summary
Each data structure has strengths and weaknesses which affect
performance depending on the task.
Arrays allow random access and require less memory per element
(do not need space for pointers) while lacking efficiency for
insertion/deletion operations and memory allocation.
On the contrary, linked lists are dynamic and have faster
insertion/deletion time complexities.
However, linked list have a slower search time and pointers require
additional memory per element in the list.
References
[1] Aaron M. Tenenbaum, Yedidyah Langsam and Moshe J. Augenstein,
“Data Structures Using C and C++”, PHI Learning Private Limited, Delhi
India
[2] Horowitz and Sahani, “Fundamentals of Data Structures”, Galgotia
Publications Pvt Ltd Delhi India.
[3] Lipschutz, “Data Structures” Schaum’s Outline Series, Tata McGraw-
hill Education (India) Pvt. Ltd.
[4] Thareja, “Data Structure Using C” Oxford Higher Education.
[5] AK Sharma, “Data Structure Using C”, Pearson Education India.
7/4/2020 Megha Gupta KCS 301: DS Unit 1 230
Thank you
7/4/2020 Megha Gupta KCS 301: DS Unit 1 231

More Related Content

What's hot

17 cpu scheduling and scheduling criteria
17 cpu scheduling and scheduling criteria 17 cpu scheduling and scheduling criteria
17 cpu scheduling and scheduling criteria myrajendra
 
Fetch decode-execute presentation
Fetch decode-execute presentationFetch decode-execute presentation
Fetch decode-execute presentationchantellemallia
 
Need for Software Engineering
Need for Software EngineeringNeed for Software Engineering
Need for Software EngineeringUpekha Vandebona
 
Software Engineering Methodologies
Software Engineering MethodologiesSoftware Engineering Methodologies
Software Engineering MethodologiesDamian T. Gordon
 
Software process Models
Software process ModelsSoftware process Models
Software process ModelsSADEED AMEEN
 
System development life cycle (sdlc)
System development life cycle (sdlc)System development life cycle (sdlc)
System development life cycle (sdlc)Mukund Trivedi
 
Domain-Specific Software Engineering
Domain-Specific Software EngineeringDomain-Specific Software Engineering
Domain-Specific Software Engineeringelliando dias
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycleGurban Daniel
 
Dbms lab manual
Dbms lab manualDbms lab manual
Dbms lab manualArthyR3
 
Graph theory narsingh deo
Graph theory narsingh deoGraph theory narsingh deo
Graph theory narsingh deoUmang Gupta
 
Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...
Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...
Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...pihavob
 
طرح درس روزانه رایانه کار پیشرفته
طرح درس روزانه رایانه کار  پیشرفتهطرح درس روزانه رایانه کار  پیشرفته
طرح درس روزانه رایانه کار پیشرفتهcomputerka
 
EE5440 – Computer Architecture - Lecture 2
EE5440 – Computer Architecture - Lecture 2EE5440 – Computer Architecture - Lecture 2
EE5440 – Computer Architecture - Lecture 2Dilawar Khan
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler DesignAkhil Kaushik
 

What's hot (20)

17 cpu scheduling and scheduling criteria
17 cpu scheduling and scheduling criteria 17 cpu scheduling and scheduling criteria
17 cpu scheduling and scheduling criteria
 
Fetch decode-execute presentation
Fetch decode-execute presentationFetch decode-execute presentation
Fetch decode-execute presentation
 
Need for Software Engineering
Need for Software EngineeringNeed for Software Engineering
Need for Software Engineering
 
Software Engineering Methodologies
Software Engineering MethodologiesSoftware Engineering Methodologies
Software Engineering Methodologies
 
Software process Models
Software process ModelsSoftware process Models
Software process Models
 
System development life cycle (sdlc)
System development life cycle (sdlc)System development life cycle (sdlc)
System development life cycle (sdlc)
 
Compiler unit 5
Compiler  unit 5Compiler  unit 5
Compiler unit 5
 
loaders and linkers
 loaders and linkers loaders and linkers
loaders and linkers
 
OS UNIT – 2 - Process Management
OS UNIT – 2 - Process ManagementOS UNIT – 2 - Process Management
OS UNIT – 2 - Process Management
 
Domain-Specific Software Engineering
Domain-Specific Software EngineeringDomain-Specific Software Engineering
Domain-Specific Software Engineering
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycle
 
Dbms lab manual
Dbms lab manualDbms lab manual
Dbms lab manual
 
Graph theory narsingh deo
Graph theory narsingh deoGraph theory narsingh deo
Graph theory narsingh deo
 
Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...
Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...
Compilers: Principles, Techniques, and Tools 2nd By Alfred V. Aho (Internatio...
 
طرح درس روزانه رایانه کار پیشرفته
طرح درس روزانه رایانه کار  پیشرفتهطرح درس روزانه رایانه کار  پیشرفته
طرح درس روزانه رایانه کار پیشرفته
 
EE5440 – Computer Architecture - Lecture 2
EE5440 – Computer Architecture - Lecture 2EE5440 – Computer Architecture - Lecture 2
EE5440 – Computer Architecture - Lecture 2
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
 
SE Unit 1
SE Unit 1SE Unit 1
SE Unit 1
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Addressing modes
Addressing modesAddressing modes
Addressing modes
 

Similar to Introduction to Data Structure

SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSRPatel10
 
Database management system lLABMANUALpdf
Database management system lLABMANUALpdfDatabase management system lLABMANUALpdf
Database management system lLABMANUALpdfBhagyavantRajapure
 
Presentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoPresentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoepandhari
 
B tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEB tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEMITAcademy1
 
Lecture plan ec202_eca-365
Lecture plan ec202_eca-365Lecture plan ec202_eca-365
Lecture plan ec202_eca-365ArunKishorJohar
 
01.B.E. CSE final.doc
01.B.E. CSE final.doc01.B.E. CSE final.doc
01.B.E. CSE final.doctsajuraj
 
B tech cse syllabus - MITAOE
B tech cse syllabus - MITAOEB tech cse syllabus - MITAOE
B tech cse syllabus - MITAOEMITAcademy1
 
data scientist course (4).pptx. excelr thane
data scientist course (4).pptx. excelr thanedata scientist course (4).pptx. excelr thane
data scientist course (4).pptx. excelr thanetejadulla96
 
ExcelR- Data Science, Data Analytics, Business Analytics Course Training Mumbai
ExcelR- Data Science, Data Analytics, Business Analytics Course Training MumbaiExcelR- Data Science, Data Analytics, Business Analytics Course Training Mumbai
ExcelR- Data Science, Data Analytics, Business Analytics Course Training Mumbaitejadulla96
 
data scientist course (4).excelr solutions
data scientist course (4).excelr solutionsdata scientist course (4).excelr solutions
data scientist course (4).excelr solutionstejadulla96
 
data scientist course (4).Excelr solutions thane
data scientist course (4).Excelr solutions thanedata scientist course (4).Excelr solutions thane
data scientist course (4).Excelr solutions thanetejadulla96
 
Roehampton computing workshop 1
Roehampton computing workshop 1Roehampton computing workshop 1
Roehampton computing workshop 1Miles Berry
 
M.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdfM.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdfhsingh5201
 

Similar to Introduction to Data Structure (20)

SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdf
 
Database management system lLABMANUALpdf
Database management system lLABMANUALpdfDatabase management system lLABMANUALpdf
Database management system lLABMANUALpdf
 
2017 b.e.-cse
2017 b.e.-cse2017 b.e.-cse
2017 b.e.-cse
 
Presentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoPresentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeo
 
B tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEB tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOE
 
Lecture plan ec202_eca-365
Lecture plan ec202_eca-365Lecture plan ec202_eca-365
Lecture plan ec202_eca-365
 
AIML-MODULE1.pdf
AIML-MODULE1.pdfAIML-MODULE1.pdf
AIML-MODULE1.pdf
 
01.b.e. cse final
01.b.e. cse final01.b.e. cse final
01.b.e. cse final
 
01.B.E. CSE final.doc
01.B.E. CSE final.doc01.B.E. CSE final.doc
01.B.E. CSE final.doc
 
B tech cse syllabus - MITAOE
B tech cse syllabus - MITAOEB tech cse syllabus - MITAOE
B tech cse syllabus - MITAOE
 
Oose lab notes
Oose lab notesOose lab notes
Oose lab notes
 
data scientist course (4).pptx. excelr thane
data scientist course (4).pptx. excelr thanedata scientist course (4).pptx. excelr thane
data scientist course (4).pptx. excelr thane
 
ExcelR- Data Science, Data Analytics, Business Analytics Course Training Mumbai
ExcelR- Data Science, Data Analytics, Business Analytics Course Training MumbaiExcelR- Data Science, Data Analytics, Business Analytics Course Training Mumbai
ExcelR- Data Science, Data Analytics, Business Analytics Course Training Mumbai
 
data scientist course (4).excelr solutions
data scientist course (4).excelr solutionsdata scientist course (4).excelr solutions
data scientist course (4).excelr solutions
 
data scientist course (4).Excelr solutions thane
data scientist course (4).Excelr solutions thanedata scientist course (4).Excelr solutions thane
data scientist course (4).Excelr solutions thane
 
Roehampton computing workshop 1
Roehampton computing workshop 1Roehampton computing workshop 1
Roehampton computing workshop 1
 
Day1 session3
Day1 session3Day1 session3
Day1 session3
 
2017 BE CSE Syllabus Anna University Affiliated Colleges
2017 BE CSE Syllabus Anna University Affiliated Colleges2017 BE CSE Syllabus Anna University Affiliated Colleges
2017 BE CSE Syllabus Anna University Affiliated Colleges
 
M.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdfM.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdf
 
Day1 session3
Day1 session3Day1 session3
Day1 session3
 

Recently uploaded

complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 

Recently uploaded (20)

complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 

Introduction to Data Structure

  • 1. Noida Institute of Engineering and Technology, Greater Noida Introduction to Arrays and Linked List Megha Gupta Assistant Professor Computer Science and Engineering Unit: 1 Data Structure Course Details (Ex: B Tech 3th Sem)
  • 2. • Be familiar with basic techniques of algorithm analysis • Be familiar with writing recursive methods • Master the implementation of linked data structures such as linked lists and binary trees • Be familiar with advanced data structures such as balanced search trees, hash tables, priority queues and the disjoint set union/find data structure • Be familiar with several sub-quadratic sorting algorithms including quicksort, mergesort and heapsort 7/4/2020 Megha Gupta KCS 301: DS Unit 1 2 Course Objective
  • 3. • Be familiar with some graph algorithms such as shortest path and minimum spanning tree • Master the standard data structure library of a major programming language • Master analyzing problems and writing program solutions to problems using the above techniques 7/4/2020 Megha Gupta KCS 301: DS Unit 1 3 Course Objective
  • 4. • CO 1 Describe how arrays, linked lists, stacks, queues, trees, and graphs are represented in memory, used by the algorithms and their common applications. • CO 2 Identify the alternative implementations of data structures with respect to its performance to solve a real world problem. • CO 3 Understanding the concept of recursion, application of recursion and its implementation and removal of recursion. • CO 4 Discuss the computational efficiency of the sorting and searching algorithms. • CO 5 Implementation of Trees and Graphs and perform various operations on these data structure. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 4 Course Outcome
  • 5. 1.Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering specialization for the solution of complex engineering problems. 2.Problem analysis: Identify, formulate, research literature, and analyse complex engineering problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences. 3.Design/development of solutions: Design solutions for complex engineering problems and design system components or processes that meet the specified needs with appropriate consideration for public health and safety, and cultural, societal, and environmental considerations. 4.Conduct investigations of complex problems: Use research based knowledge and research methods including design of experiments, analysis and interpretation of data, and synthesis of information to provide valid conclusions. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 5 Program Outcomes
  • 6. 5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools, including prediction and modeling to complex engineering activities, with an understanding of the limitations. 6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice. 7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development. 8.Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering practice. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 6 Program Outcomes
  • 7. 9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in multidisciplinary settings. 10. Communication: Communicate effectively on complex engineering activities with the engineering community and with the society at large, such as, being able to comprehend and write effective reports and design documentation, make effective presentations, and give and receive clear instructions. 11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary environments. 12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-long learning in the broadest context of technological change. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 7 Program Outcomes
  • 8. On successful completion of graduation degree the Computer Science & Engineering graduates will be able to: PSO1: The ability to design and develop the Hardware and Software systems. PSO2: An understanding of interdisciplinary computing techniques and an ability to apply them in the design of advanced computing. PSO3: An understanding of programming methodology software development paradigms, design and analysis of Algorithms, Operating Systems, Digital Logic Design, Theory of Computation, Discrete Mathematics, Compiler Design, etc. PSO4: The ability to integrate & manage the various phases/components of software development projects of society. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 8 Program Specific Outcomes
  • 9. • PEO 1: To have an excellent scientific and engineering breadth so as to comprehend, analyze, design and solve real-life problems using state-of-the-art technologies. • PEO 2: To lead a successful career in industries, to pursue higher studies or to support entrepreneurial endeavors so that engineering graduates can face the global challenges. • PEO 3: To effectively bridge the gap between industry and academia through effective communication skill, professional attitude, ethical values and a desire to learn. • PEO 4: To provide highly competitive environment and solidarity to students for successful professional career as engineer, scientist, entrepreneur and bureaucrats for the betterment of society. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 9 Program Education Objectives
  • 10. Sr. No Course Outcome PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 1 CO 1 3 3 3 3 3 2 1 1 3 2 2 1 2 CO 2 3 3 3 3 3 2 1 1 3 1 2 1 3 CO 3 3 3 3 3 3 2 1 1 3 1 2 1 4 CO 4 3 3 3 3 3 2 1 1 3 1 2 1 5 CO 5 3 3 3 3 3 2 1 1 3 1 2 1 7/4/2020 Megha Gupta KCS 301: DS Unit 1 10 CO-PO Mapping
  • 11. Sr. No Course Outcome PSO1 PSO2 PSO3 PSO4 1 CO 1 3 2 3 3 2 CO 2 2 3 2 3 3 CO 3 2 2 3 2 4 CO 4 2 2 3 1 5 CO 5 3 1 3 2 7/4/2020 Megha Gupta KCS 301: DS Unit 1 11 CO-PSO Mapping
  • 12. • Introduction: Basic Terminology, Elementary Data Organization, Built in Data Types in C. • Algorithm, Efficiency of an Algorithm, Time and Space Complexity, Asymptotic notations: Big • Oh, Big Theta and Big Omega, Time-Space trade-off. Abstract Data Types (ADT) • Arrays: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row Major • Order, and Column Major Order, Derivation of Index Formulae for 1- D,2-D,3-D and n-D Array • Application of arrays, Sparse Matrices and their representations. UNIT-1 Syllabus 7/4/2020 Megha Gupta KCS 301: DS Unit 1 12
  • 13. • Linked lists: Array Implementation and Pointer Implementation of Singly Linked Lists, Doubly • Linked List, Circularly Linked List, Operations on a Linked List. Insertion, Deletion, Traversal, • Polynomial Representation and Addition Subtraction & Multiplications of Single variable & Two • variables Polynomial. UNIT-1 Syllabus 7/4/2020 Megha Gupta KCS 301: DS Unit 1 13
  • 14. Topics Duration (in Hours) Basic Terminology 1 Elementary Data Organization Built in Data Types in C. 1 Algorithm, Efficiency of an Algorithm 1 Time and Space Complexity 1 Asymptotic notations: Big Oh, Big Theta and Big Omega 1 Time-Space trade-off. 1 Abstract Data Types (ADT) 1 Arrays 1 Single and Multidimensional Arrays 1 Contents 7/4/2020 Megha Gupta KCS 301: DS Unit 1 14
  • 15. Topics Duration (in Hours) Representation of Arrays: Row Major Order, and Column Major Order 1 Derivation of Index Formulae for 1-D,2-D,3-D and n-D Array 1 Sparse Matrices and their representations. 1 Representation of Arrays: Row Major Order, and Column Major Order 1 Derivation of Index Formulae for 1-D,2-D,3-D and n-D Array 1 Sparse Matrices and their representations. 1 Contents 7/4/2020 Megha Gupta KCS 301: DS Unit 1 15
  • 16. Topics Duration (in Hours) Linked lists: Array Implementation Pointer Implementation of Singly Linked Lists 1 Doubly Linked List 1 Circularly Linked List 1 Polynomial Representation 1 Contents 7/4/2020 Megha Gupta KCS 301: DS Unit 1 16
  • 17. Objective of the course is to make students able to: • Learn the basic types for data structure, implementation and application. • Know the strength and weakness of different data structures. • Use the appropriate data structure in context of solution of given problem • Develop programming skills which require to solve given problem. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 17 Objective of Unit
  • 18. • Repetition statements (loops)-while, for, do-while statements, Loop examples • Functions-Designing Structured Programs, Functions, user defined functions. • Pointers – Introduction (Basic Concepts), Pointers for inter function communication, pointers to pointers, compatibility, Pointer Applications-Arrays and Pointers, Pointer Arithmetic and arrays, Passing an array to a function, memory allocation functions, array of pointers, programming applications. • Basics of Structures, Arrays of Structures, Pointers to Structures, Self-referential Structures. • Dynamic Memory Allocation, Allocating Memory with malloc, Allocating Memory with calloc, Freeing Memory, Reallocating Memory Block 7/4/2020 Megha Gupta KCS 301: DS Unit 1 18 Prerequisite and Recap
  • 19. Topic mapping with Course Outcome 7/4/2020 19 Array and Linked List(CO1) Topic CO1 CO2 CO3 CO4 CO5 Array 1 - - - - Linked List 1 - - - - Megha Gupta KCS 301: DS Unit 1
  • 20. Basic Terminologies • Data: are simply a value are set of values of different type which is called data types like string, integer, char etc. • Structure: Way of organizing information, so that it is easier to use. • In simple words we can define DATA STRUCTURES as its a way organizing data in such a way so that data can be easier to use. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 20 Introduction
  • 21. Definition • Data Structure .. A data structure is a particular way of organizing data in a computer so that it can be used efficiently. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 21 Introduction
  • 22. Why Data Structure 7/4/2020 Megha Gupta KCS 301: DS Unit 1 22 Introduction
  • 23. Why Data Structure • Human requirement with computer are going to complex day by day. To solve the complex requirements in efficient way we need this study. • Provide fastest solution of human requirements. • Provide efficient solution of complex problem. >Space >Time 7/4/2020 Megha Gupta KCS 301: DS Unit 1 23 Introduction
  • 24. Classification of Data Structure 7/4/2020 Megha Gupta KCS 301: DS Unit 1 24 Introduction
  • 25. Classification of Data Structure ... • Simple Data Structure / Primitive data structure: used to represent the standard data types of any one of the computer languages (integer, Character, float etc.). • Compound Data Structure / Non Primitive Data Structure: can be constructed with the help of any one of the primitive data structure and it is having a specific functionality. It can be designed by user. It can be classified as Linear and Non-Linear Data Structure. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 25 Introduction
  • 26. Classification of Data Structure ... • Linear Data Structures: A linear data structure traverses the data elements sequentially, in which only one data element can directly be reached. Ex: Arrays, Linked Lists. • Non-Linear Data Structures: Every data item is attached to several other data items in a way that is specific for reflecting relationships. The data items are not arranged in a sequential structure. Ex: Trees, Graphs 7/4/2020 Megha Gupta KCS 301: DS Unit 1 26 Introduction
  • 27. Operation on Linear/Non-Linear Data Structure • Add an element • Delete an element • Traverse / Display • Sort the list of elements • Search for a data element 7/4/2020 Megha Gupta KCS 301: DS Unit 1 27 Introduction
  • 28. Types of Linear Data Structure • Array: An array is the collection of the variables of the same data type that are referenced by the common name. • int A[10], char B[10] 7/4/2020 Megha Gupta KCS 301: DS Unit 1 28 Introduction
  • 29. Types of Linear Data Structure…. • Stack Stack is a linear data structure in which the insertion and deletion operations are performed at only one end. In a stack, adding and removing of elements are performed at a single position which is known as “top”. That means, a new element is added at top of the stack and an element is removed from the top of the stack. In stack, the insertion and deletion operations are performed based on LIFO(Last In First Out) principle. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 29 Introduction
  • 30. Types of Linear Data Structure… • Queue is a linear data structure in which the insertion and deletion operations are performed at two different ends. • The insertion is performed at one end and deletion is performed at another end. • In a queue data structure, the insertion operation is performed at a position which is known as “rear” and the deletion operation is performed at a position which is known as 'front'. • In queue data structure, the insertion and deletion operations are performed based on FIFO (First In First Out) principle.7/4/2020 Megha Gupta KCS 301: DS Unit 1 30 Introduction
  • 31. Types of Linear Data Structure… • LINKED LIST When we want to work with an unknown number of data values, we use a linked list data structure to organize that data. The linked list is a linear data structure that contains a sequence of elements such that each element links to its next element in the sequence. Each element in a linked list is called "Node". 7/4/2020 Megha Gupta KCS 301: DS Unit 1 31 Introduction
  • 32. Types of NON Linear Data Structure • Tree is a non-linear data structure which organizes data in hierarchical structure. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 32 Introduction
  • 33. Types of NON Linear Data Structure.. • Graph is a non-linear data structure. It contains a set of points known as nodes (or vertices) and a set of links known as edges (or Arcs). Here edges are used to connect the vertices. • Generally, a graph G is represented as G = ( V , E ), where V is set of vertices and E is set of edges. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 33 Introduction
  • 34. What is an Array • An array is the collection of the variable of the same type that are referenced by the common name. • An array is the derived data type. • Consist of contiguous memory locations. • Lowest address corresponds to first element while highest address corresponds to last element. • Can have data item of type int, float, char, double etc. also have user derived data type like: structure, union. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 34 Introduction to Array
  • 35. Need for an Array • To store large number of array of variables of same type under a single variable. • Eg. To store Marks of 50 Students Record of sales of 100 salesman 7/4/2020 Megha Gupta KCS 301: DS Unit 1 35 Introduction to Array
  • 36. Types of Arrays in C • In c programming language, arrays are classified into two types. They are as follows... > Single Dimensional Array / One Dimensional Array > Multi Dimensional Array Declaration of Single Dimensional Array • datatype arrayName [ size ] ; • int rollNumbers [60] ; Initialization of Single Dimensional Array • datatype arrayName [ size ] = {value1, value2, ...} ; • int marks [6] = { 89, 90, 76, 78, 98, 86 } ; • int marks [] = { 88,96,89, 90, 76, 78, 98, 86 } ; Accessing Elements of Single Dimensional Array A[2]=99; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 36 Introduction to Array
  • 37. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 37 Introduction to Array
  • 38. • Array of an element of an array say “A[ I ]” is calculated using the following formula: • Address of A [ I ] = B + W * ( I – LB ) • Where, B = Base address W = Storage Size of one element stored in the array (in byte) I = Subscript of element whose address is to be found LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 38 Introduction to Array
  • 39. Example: • Given the base address of an array B[1300…..1900] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700]. • Solution: The given values are: B = 1020, LB = 1300, W = 2, I = 1700 Address of A [ I ] = B + W * ( I – LB ) = 1020 + 2 * (1700 – 1300) = 1020 + 2 * 400 = 1020 + 800 = 1820 [Ans] 7/4/2020 Megha Gupta KCS 301: DS Unit 1 39 Introduction to Array
  • 40. • Find the base address of an array A[-15:65]. The size of each element is 2 bytes in the memory and the location of A[37] is 4279. Solution: The given values are: LB = -15, UB = 65, W = 2, I = 37, A[37] = 4279 Address of A [ I ] = B + W * ( I – LB ) 4279= B + 2 * (37 – (-15)) 4279= B + 2 * 52 4279= B + 104 B= 4175 [Ans] 7/4/2020 Megha Gupta KCS 301: DS Unit 1 40 Introduction to Array
  • 41. Creating an array in C #include<stdio.h> void main() { int a[10],i,n; printf("nEnter number of elements"); scanf("%d",&n); printf("n Enter %d elementsn",n); for(i=0;i<n;i++){ scanf("%d",&a[i]); } for(i=0;i<n;i++){ printf("n%d",a[i]); } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 41 Introduction to Array
  • 42. Passing array to function • Passing array to function using call by value method. • Passing array to function using call by reference. • Passing entire array to a function as an argument. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 42 Introduction to Array
  • 43. Passing array to function using call by value method #include <stdio.h> void disp( char ch) { printf("%c ", ch); } void main() { char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}; for (int x=0; x<10; x++) { /* I’m passing each element one by one using subscript*/ disp (arr[x]); } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 43 Introduction to Array
  • 44. Passing array to function using call by reference #include <stdio.h> void disp( int *num) { printf("%d ", *num); } void main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; for (int i=0; i<10; i++) { /* Passing addresses of array elements*/ disp (&arr[i]); } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 44 Introduction to Array
  • 45. Passing an entire array to a function #include <stdio.h> float average(float age[]); int main() { float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18}; avg = average(age); //Only name of an array is passed //as an argument printf("Average age = %.2f", avg); return 0; } float average(float age[]) { int i; float avg, sum = 0.0; for (i = 0; i < 6; ++i) { sum += age[i]; } avg = (sum / 6); return avg; } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 45 Introduction to Array
  • 46. Write a program in c to find max element in the array using function. #include <stdio.h> #include <conio.h> int max(int [],int); void main() { int a[]={10,5,45,12,19}; int n=5,m; clrscr(); m=max(a,n); printf("nMAXIMUM NUMBER IS %d",m); getch(); } int max(int x[],int k) { int t,i; t=x[0]; for(i=1;i<k;i++) { if(x[i]>t) t=x[i]; } return(t); } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 46 Introduction to Array
  • 47. Searching For an Element in an Array • There are two ways to search an element: Linear Search > Check each element of an array. > If the match found – element exists, else does not exist. > Suitable for small lists since time consuming > Suitable for unsorted Lists. Binary Search > Most Important preconditions is that the list should be sorted. > Suitable for arrays with long list of elements 7/4/2020 Megha Gupta KCS 301: DS Unit 1 47 Introduction to Array
  • 48. Linear Search • The linear search is a sequential search, which uses a loop to step through an array, starting with the first element. • It compares each element with the value being searched for, and stops when either the value is found or the end of the array is encountered. • If the value being searched is not in the array, the algorithm will unsuccessfully search to the end of the array. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 48 Introduction to Array
  • 49. Advantages • The linear search is simple - It is very easy to understand and implement. • It does not require the data in the array to be stored in any particular order. Disadvantages • It has very poor efficiency because it takes lots of comparisons to find a particular record in big files. • The performance of the algorithm scales linearly with the size of the input . • Linear search is slower then other searching algorithms. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 49 Introduction to Array
  • 50. Linear Search Example 7/4/2020 Megha Gupta KCS 301: DS Unit 1 50 Introduction to Array
  • 51. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 51 Introduction to Array
  • 52. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 52 Introduction to Array
  • 53. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 53 Introduction to Array
  • 54. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 54 Introduction to Array
  • 55. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 55 Introduction to Array
  • 56. #include <stdio.h> int search(int arr[], int n, int x) ; void main( ) { int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); int result = search(arr, n, x); (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 56 Introduction to Array
  • 57. int search(int arr[], int n, int x) { int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1; } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 57 Introduction to Array
  • 58. Analysis of Linear Search How long will our search take? • In the best case, the target value is in the first element of the array. So the search takes some tiny, and constant, amount of time. • In the worst case, the target value is in the last element of the array. So the search takes an amount of time proportional to the length of the array. O(n) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 58 Introduction to Array
  • 59. Analysis of Linear Search • In the average case, the target value is somewhere in the array. • In fact, since the target value can be anywhere in the array, any element of the array is equally likely. • So on average, the target value will be in the middle of the array. • So the search takes an amount of time proportional to half the length of the array. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 59 Introduction to Array
  • 60. Binary Search The general term for a smart search through sorted data is a binary search. 1. The initial search region is the whole array. 2. Look at the data value in the middle of the search region. 3. If you’ve found your target, stop. 4. If your target is less than the middle data value, the new search region is the lower half of the data. 5. If your target is greater than the middle data value, the new search region is the higher half of the data. 6. Continue from Step 2. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 60 Introduction to Array
  • 61. Binary Search Example 7/4/2020 Megha Gupta KCS 301: DS Unit 1 61 Introduction to Array
  • 62. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 62 Introduction to Array
  • 63. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 63 Introduction to Array
  • 64. #include <stdio.h> void main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements:n"); scanf("%d",&n); printf("Enter %d integers:n", n); for (c = 0; c < n; c++) scanf("%d",&array[c]); printf("Enter the value to find:n"); scanf("%d", &search); first = 0;last = n - 1; middle = (first+last)/2; while (first <= last) { if (array[middle] < search) first = middle + 1; else if (array[middle] == search) { printf("%d is present at index %d.n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } if (first > last) printf("Not found! %d is not present in the list.n", search); } Binary Search Program 7/4/2020 Megha Gupta KCS 301: DS Unit 1 64 Introduction to Array
  • 65. Time complexity of binary search At each iteration, the array is divided by half. So let’s say the length of array at any iteration is n At Iteration 1, Length of array = n At Iteration 2, Length of array = n⁄2 At Iteration 3, Length of array = (n⁄2)⁄2 = n⁄22 Therefore, after Iteration k, Length of array = n⁄2k Also, we know that after After k divisions, the length of array becomes 1 Therefore Length of array = n⁄2k = 1 => n = 2k Applying log function on both sides: => log2 (n) = log2 (2k) => log2 (n) = k log2 (2) => k = log2 (n) Hence the time complexity of Binary Search is log2 (n) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 65 Introduction to Array
  • 66. Insert element in array • Example • Input Input array elements: 10, 20, 30, 40, 50 Input element to insert: 35 Input position where to insert: 4 Output Elements of array are: 10, 20, 30, 35, 40, 50 7/4/2020 Megha Gupta KCS 301: DS Unit 1 66 Introduction to Array
  • 67. Logic to insert element in array Insert an element at position 4. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 67 Introduction to Array
  • 68. Logic to insert element in array for(i=size; i>=pos; i--) arr[i] = arr[i - 1]; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 68 Introduction to Array
  • 69. arr[pos - 1] = num; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 69 Introduction to Array
  • 70. Program to insert element in array #include <stdio.h> #define MAX_SIZE 100 int main() { int arr[MAX_SIZE]; int i, size, num, pos; printf("Enter size of the array : "); scanf("%d", &size); printf("Enter elements in array : "); 7/4/2020 Megha Gupta KCS 301: DS Unit 1 70 for(i=0; i<size; i++) scanf("%d", &arr[i]); printf("Enter element to insert : "); scanf("%d", &num); printf("Enter the element position : "); scanf("%d", &pos); if(pos > size+1 || pos <= 0) { printf("Invalid position! Please enter position between 1 to %d", size); } Introduction to Array
  • 71. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 71 else { /* Make room for new array element by shifting to right */ for(i=size; i>=pos; i--) { arr[i] = arr[i-1]; } /* Insert new element at given position and increment size */ arr[pos-1] = num; size++; /* Print array after insert operation */ printf("Array elements after insertion : "); for(i=0; i<size; i++) { printf("%dt", arr[i]); } } return 0; } Introduction to Array
  • 72. Delete element from an array • Example • Input Input array elements: 10 20 30 40 50 Input position to delete: 2 Output Array elements: 10, 30, 40, 50 7/4/2020 Megha Gupta KCS 301: DS Unit 1 72 Introduction to Array
  • 73. Logic to remove element from array •Step by step descriptive logic to remove element from array. •Move to the specified location which you want to remove in given array. •Copy the next element to the current element of array. Which is you need to perform array[i] = array[i + 1]. •Repeat above steps till last element of array. •Finally decrement the size of array by one. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 73 Introduction to Array
  • 74. #include <stdio.h> #define MAX_SIZE 100 int main() { int arr[MAX_SIZE]; int i, size, pos; printf("Enter size of the array : "); scanf("%d", &size); printf("Enter elements in array : "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } Program to delete an element from an array 7/4/2020 Megha Gupta KCS 301: DS Unit 1 74 Introduction to Array printf("Enter the element position to delete : "); scanf("%d", &pos); if(pos < 0 || pos > size) { printf("Please enter position between 1 to %d", size); }
  • 75. else { for(i=pos; i<=size-1; i++){ arr[i-1] = arr[i]; } size--; } printf("nElements of array after delete are : "); for(i=0; i<size; i++) { printf("%dt", arr[i]); } return 0; } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 75 Introduction to Array
  • 76. Multi-dimensional Arrays in C • Multidimensional array declaration type name[size1][size2]...[sizeN]; • For example, the following declaration creates a three dimensional integer array − int threedim[5][10][4]; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 76 Introduction to Array
  • 77. Two dimensional (2D) arrays • An array of arrays is known as 2D array. • The two dimensional (2D) array in C programming is also known as matrix. • A matrix can be represented as a table of rows and columns. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 77 Introduction to Array
  • 78. Initializing Two-Dimensional Arrays • Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; • The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the previous example − int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 78 Introduction to Array
  • 79. Things that you must consider while initializing a 2D array • /* Valid declaration*/ int abc[2][2] = {1, 2, 3 ,4 } • /* Valid declaration*/ int abc[][2] = {1, 2, 3 ,4 } • /* Invalid declaration – you must specify second dimension*/ int abc[][] = {1, 2, 3 ,4 } • /* Invalid because of the same reason mentioned above*/ int abc[2][] = {1, 2, 3 ,4 } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 79 Introduction to Array
  • 80. Accessing Two-Dimensional Array Elements • An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example : int val = a[2][3]; #include <stdio.h> void main () { int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j; for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf("a[%d][%d] = %dn", i,j, a[i][j] ); } } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 80 Introduction to Array
  • 81. To store the elements entered by user in 2D Array #include<stdio.h> void main() { int abc[5][4]; int i, j; for(i=0; i<5; i++) { for(j=0;j<4;j++) { printf("Enter value for abc[%d][%d]:", i, j); scanf("%d", &abc[i][j]); } } }7/4/2020 Megha Gupta KCS 301: DS Unit 1 81 Introduction to Array
  • 82. Address Calculation in Two Dimensional Array: 7/4/2020 Megha Gupta KCS 301: DS Unit 1 82 Introduction to Array
  • 83. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 83 Introduction to Array
  • 84. Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given: Row Major System: Address of A [ I1 ][ I2 ] = B + W * [( I1 – L1 ) * N2+ ( I2 – L2 )] Column Major System: Address of A [ I1 ][ I2 ] Column Major Wise = B + W * [( I1 – L1 ) + N1 * ( I2 – L2 )] Where, B = Base address I1 = Row subscript of element whose address is to be found I2 = Column subscript of element whose address is to be found W = Storage Size of one element stored in the array (in byte) L1 = Lower limit of row/start row index of matrix, if not given assume 0 (zero) L2 = Lower limit of column/start column index of matrix, if not given assume 0 (zero) N1 = Number of row of the given matrix N2 = Number of column of the given matrix7/4/2020 Megha Gupta KCS 301: DS Unit 1 84 Introduction to Array
  • 85. Q 1. An array X [-15……….10, 15……………40] requires one byte of storage. If beginning location is 1500 determine the location of X [15][20]. As you see here the number of rows and columns are not given in the question. So they are calculated as: Number or rows say N1 = (U1 – L1) + 1 = [10 – (- 15)] +1 = 26 Number or columns say N2 = (U2 – L2) + 1 = [40 – 15)] +1 = 26 (i) Column Major Wise Calculation of above equation The given values are: B = 1500, W = 1 byte, I1 = 15, I2 = 20, L1 = -15, L2 = 15, N1 = 26 Address of A [ I1 ][ I2 ] =B + W * [( I1 – L1 ) + N1 * ( I2 – L2 )] = 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)] = 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160] = 1660 [Ans] 7/4/2020 Megha Gupta KCS 301: DS Unit 1 85 Introduction to Array
  • 86. Q 1. An array X [-15……….10, 15……………40] requires one byte of storage. If beginning location is 1500 determine the location of X [15][20]. (ii) Row Major Wise Calculation of above equation The given values are: B = 1500, W = 1 byte, I1 = 15, I2 = 20, L1 = -15, L2 = 15, N2 = 26 Address of A [ I1 ][ I2 ] =B + W * [( I1 – L1 )* N2 + ( I2 – L2 )] = 1500 + 1* [26 * (15 – (-15))) + (20 – 15)] = 1500 + 1 * [26 * 30 + 5] = 1500 + 1 * [780 + 5] = 1500 + 785 = 2285 [Ans] 7/4/2020 Megha Gupta KCS 301: DS Unit 1 86 Introduction to Array
  • 87. Three-Dimensional Array 7/4/2020 Megha Gupta KCS 301: DS Unit 1 87 Introduction to Array
  • 88. Given an array [ 1..8, 1..5, 1..7 ] of integers. Calculate address of element A[5,3,6], by using rows wise methods, if Base Address=900? Solution:- The dimensions of A are : N1=8 , N2=5, N3=7, I1=5, I2=3, I3=6, W=2,L1=1,L2=1,L3=1 Rows - wise : Location (A[I1, I2, I3]) = B + W*[(E1N2+E2)*N3+E3] = B + W*[((I1-L1)*N2+(I2-L2))*N3+(I3-L3)] Location(A[5,3,6])= 900 + 2*[((5-1)*5+(3-1))*7+(6-1)] = 900 + 2*[(4*5+2)*7+5] = 900 +2*159 = 1218 7/4/2020 Megha Gupta KCS 301: DS Unit 1 88 Introduction to Array
  • 89. Initializing Three-Dimensional Array Method 1: int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}; Method 2: int x[2][3][4] = { { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} }, { {12,13,14,15}, {16,17,18,19}, {20,21,22,23} } }; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 89 Introduction to Array
  • 90. Applications of Arrays in C ● Arrays are used to Store List of values ● Arrays are used to Perform Matrix Operations ● Arrays are used to implement Search Algorithms Linear Search Binary Search ● Arrays are used to implement Sorting Algorithms. Insertion Sort Bubble Sort Selection Sort Quick Sort Merge Sort, etc., ● Arrays are used to implement Data structures. Stack Using Arrays Queue Using Arrays ● Arrays are also used to implement CPU Scheduling Algorithms. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 90 Introduction to Array
  • 91. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 91 Sorting Using Array Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Bubble Sort
  • 92. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 92 Bubble sort Illustration Sorting Using Array
  • 93. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 93 C Program for Bubble Sort Sorting Using Array // A function to implement bubble sort void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n-1; i++) // Last i elements are already in place for (j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); } #include <stdio.h> void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; }
  • 94. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 94 // Driver program to test above functions int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); printf("Sorted array: n"); printArray(arr, n); return 0; } C Program for Bubble Sort Sorting Using Array /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("n"); }
  • 95. Insertion Sort Example 7/4/2020 Megha Gupta KCS 301: DS Unit 1 95 Sorting Using ArraySorting Using Array
  • 96. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 96 Sorting Using Array
  • 97. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 97 Sorting Using Array #include <math.h> #include <stdio.h> /* Function to sort an array using insertion sort*/ void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }
  • 98. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 98 Sorting Using Array // A utility function to print an array of size n void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("n"); } /* Driver program to test insertion sort */ int main() { int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0; }
  • 99. The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which is already sorted. 2) Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 99 Sorting Using Array Selection Sort
  • 100. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 100 Sorting Using Array Selection Sort Example
  • 101. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 101 Sorting Using Array #include <stdio.h> void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); } } C Program for Selection Sort
  • 102. Sparse Matrix • Any matrix is called as Sparse Matrix in C, if it contains more number of zeros. • The mathematical formula behind this C Sparse Matrix is: T >= (m * n )/2 where T is total number of zeros. • 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.. • Sparse Matrix Representations Triplet Representation (Array Representation) Linked Representation 7/4/2020 Megha Gupta KCS 301: DS Unit 1 102 Introduction to Array
  • 103. Triplet Representation (Array Representation) • In this representation, we consider only non-zero values along with their row and column index values. In this representation, the 0throw stores total number of rows, total number of columns and the total number of non-zero values in the sparse matrix. For example, consider a matrix of size 5 X 6 containing 6 number of non-zero values. This matrix can be represented as shown in the image. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 103 Introduction to Array
  • 104. C Program that will convert 2D-representation to Sparse representation. #include <stdio.h> void read_matrix(int a[10][10], int r, int c); void print_sparse(int b[20][3]); void create_sparse(int a[10][10], int r, int c, int b[20][3]); void main() { int a[10][10], b[20][3], r, c; printf("nEnter the size of matrix "); scanf("%d%d", &r, &c); read_matrix(a, r, c); create_sparse(a, r, c, b); print_sparse(b); } void read_matrix(int a[10][10], int r, int c) { int i, j; printf("nEnter elements of matrixn"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { printf("[%d][%d]: ", i, j); scanf("%d", &a[i][j]); } } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 104 Introduction to Array
  • 105. void create_sparse(int a[10][10], int r, int c, int b[MAX][3]) { int i, j, k=1; b[0][0] = r; b[0][1] = c; for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { if (a[i][j] != 0) { b[k][0] = i; b[k][1] = j; b[k][2] = a[i][j]; k++; } } b[0][2] = k - 1; } } void print_sparse(int b[MAX][3]) { int i, c; c = b[0][2]; printf("nSparse form - list of 3 triplesnn"); for (i = 0; i <= c; i++) { printf("%dt%dt%dn", b[i][0], b[i][1], b[i][2]); } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 105 Introduction to Array
  • 106. Linked 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 7/4/2020 Megha Gupta KCS 301: DS Unit 1 106 Introduction to Array
  • 107. Algorithms • Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. • Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 107 Introduction to Algorithms
  • 108. Characteristics of an Algorithm • Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning. • Input − An algorithm should have 0 or more well-defined inputs. • Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output. • Finiteness − Algorithms must terminate after a finite number of steps. • Independent − An algorithm should have step-by-step directions, which should be independent of any programming code 7/4/2020 Megha Gupta KCS 301: DS Unit 1 108 Introduction to Algorithms
  • 109. Example: An algorithm to sum N natural numbers. Sum(A[],n) { s=0; for(i=1 to n) do s=s+A[i] return s } An algorithm to add to matrix Matrixadd(A[][],B[][],C[][],m,n) { for(i=1 to n) do for(j=1 to n) do c[i][j]=a[i][j]+b[i][j] } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 109 Introduction to Algorithms
  • 110. Algorithm for Insertion Sort Insertion( A,n) { for(i=1 to n-1) { k=A[i] j=i-1 while(j>0 && k< A[j]) { A[j+1]= A[j] j=j-1 } A[j+1] = t } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 110 Introduction to Algorithms
  • 111. Performance analysis of an algorithm • Space required to complete the task of that algorithm (Space Complexity). • Time required to complete the task of that algorithm (Time Complexity) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 111 Introduction to Algorithms
  • 112. Space Complexity When we design an algorithm to solve a problem, it needs some computer memory to complete its execution. For any algorithm, memory is required for the following purposes... 1. To store program instructions. 2. To store constant values. 3. To store variable values. 4. And for few other things like function calls, jumping statements etc,. Total amount of computer memory required by an algorithm to complete its execution is called as space complexity of that algorithm 7/4/2020 Megha Gupta KCS 301: DS Unit 1 112 Introduction to Algorithms
  • 113. Time Complexity • Every algorithm requires some amount of computer time to execute its instruction to perform the task. This computer time required is called time complexity. The time complexity of an algorithm can be defined as follows... • The time complexity of an algorithm is the total amount of time required by an algorithm to complete its execution. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 113 Introduction to Algorithms
  • 114. Example 1 int sum(int a, int b) { return a+b; } Space Complexity – In the above piece of code, it requires 2 bytes of memory to store variable 'a' and another 2 bytes of memory is used for return value. That means, totally it requires 4 bytes of memory to complete its execution. And this 4 bytes of memory is fixed for any input value of 'a'. This space complexity is said to be Constant Space Complexity. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 114 Introduction to Algorithms
  • 115. Time Complexity – • It requires 1 unit of time to calculate a+b and 1 unit of time to return the value. That means, totally it takes 2 units of time to complete its execution • If any program requires a fixed amount of time for all input values then its time complexity is said to be Constant Time Complexity. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 115 Introduction to Algorithms
  • 116. Example 2 int sum(int A[ ], int n) { int sum = 0, i; for(i = 0; i < n; i++) sum = sum + A[i]; return sum; } In the above piece of code it requires 'n*2' bytes of memory to store array variable 'a[ ]' 2 bytes of memory for integer parameter 'n' 4 bytes of memory for local integer variables 'sum' and 'i' (2 bytes each) 2 bytes of memory for return value. That means, totally it requires '2n+8' bytes of memory to complete its execution. Here, the total amount of memory required depends on the value of 'n'. As 'n' value increases the space required also increases proportionately. This type of space complexity is said to be Linear Space Complexity. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 116 Introduction to Algorithms
  • 117. If the amount of time required by an algorithm is increased with the increase of input value then that time complexity is said to be Linear Time Complexity. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 117 Introduction to Algorithms
  • 118. Time Space Tradeoff 7/4/2020 Megha Gupta KCS 301: DS Unit 1 118 Introduction to Algorithms
  • 119. Asymptotic Notations • Asymptotic analysis of an algorithm refers to defining the mathematical boundation/framing of its run-time performance. • Using asymptotic analysis, we can very well conclude the best case, average case, and worst case scenario of an algorithm. • Types of Asymptotic Notation 1. Big Oh(O) 2. Big Omega (Ω) 3. Theta (Θ) 4. Small Oh(o) 5. Small Omega (w) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 119 Introduction to Algorithms
  • 120. Purpose of Asymptotic Notations 1. To simplify the running time of the function 2. To describe the behavior of the function. 3. To provide asymptotic bound. 4. To describe how the running time of an algorithm increases with increase in input size 7/4/2020 Megha Gupta KCS 301: DS Unit 1 120 Introduction to Algorithms
  • 121. Big O Notation(O) • It provide asymptotic upper bound (worst case running time ) to a function. O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 <= f(n) <= c*g(n) for all n >= n0} 7/4/2020 Megha Gupta KCS 301: DS Unit 1 121 Introduction to Algorithms
  • 122. Q1 f(n) = 3n + 4, g(n) = n, Prove f(n) = O(g(n)) Sol. To prove f(n) = O(g(n)) i.e. f(n) <= c.g(n) It means 3n + 4 <=c.n Let c= 5 n f(n) c. g(n) 3n+4 5n 1 7 > 5 2 10 = 10 3 13 < 15 4 16 < 20 So, for n0 = 2 f(n) < = 5.g(n) Hence f(n) = O(g(n)) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 122 Introduction to Algorithms
  • 123. Big Omega Notation(Ω) • This notation is known as the lower bound of the algorithm, or a Best Case of an algorithm. Ω (g(n)) = {f(n): there exist positive constants c and n0 such that 0 <= c*g(n) <= f(n) for all n >= n0}. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 123 Introduction to Algorithms
  • 124. Theta Notation(Θ) • The theta notation bounds a functions from above and below, so it defines exact asymptotic behavior. Θ(g(n)) = {f(n): there exist positive constants c1, c2 and n0 such that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0} 7/4/2020 Megha Gupta KCS 301: DS Unit 1 124 Introduction to Algorithms
  • 125. Small o Notation(o) • Small-o, commonly written as o, is an Asymptotic Notation to denote the upper bound (that is not asymptotically tight) on the growth rate of runtime of an algorithm. o(g(n)) = { f(n): there exist positive constants c and n0 such that 0 <= f(n) < c*g(n) for all n >= n0} • Another definition for o notation: f(n) = o(g(n)) if and only if lim(n→∞)f(n)/g(n)=0 7/4/2020 Megha Gupta KCS 301: DS Unit 1 125 Introduction to Algorithms
  • 126. Small omega Notation(w) • Small-omega, commonly written as w, is an Asymptotic Notation to denote the lower bound (that is not asymptotically tight) on the growth rate of runtime of an algorithm. w(g(n)) = { f(n): there exist positive constants c and n0 such that f(n) > c*g(n)>=0 for all n >= n0} • Another definition for o notation: f(n) = o(g(n)) if and only if lim(n→∞)g(n)/f(n)=0 7/4/2020 Megha Gupta KCS 301: DS Unit 1 126 Introduction to Algorithms
  • 127. Self Made Video Linked: Youtube/other Video Links • https://www.youtube.com/watch?v=zWg7U0OEAoE&list=PLBF3763AF2E1C572F&index=1 • https://www.youtube.com/watch?v=aGjL7YXI31Q&list=PLEbnTDJUr_IeHYw_sfBOJ6gk5pie0yP-0 • https://www.youtube.com/watch?v=FEnwM-iDb2g&list=PLEbnTDJUr_IeHYw_sfBOJ6gk5pie0yP-0&index=2 • https://www.youtube.com/watch?v=HEjmH9wKiMo&list=PLEbnTDJUr_IeHYw_sfBOJ6gk5pie0yP-0&index=6 • https://www.youtube.com/watch?v=sr_bR1WwcLY • https://www.youtube.com/watch?v=puMz5Jt96sg • https://www.youtube.com/watch?v=d_XvFOkQz5k&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=1 • https://www.youtube.com/watch?v=KELqVT7hjeE&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=2 • https://www.youtube.com/watch?v=CZYR2v8rYLA&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=3 • https://www.youtube.com/watch?v=-lY4_THb2wM&list=PLhb7SOmGNUc5AZurO-im4t_RDr-ymjz0d&index=4 7/4/2020 Megha Gupta KCS 301: DS Unit 1 127 Faculty Video Links, Youtube & NPTEL Video Links and Online Courses Details
  • 128. Q.1 What is a data structure? Q.2 What does abstract data type means? Q.3 Explain about the types of linked lists Q.4 Write an algorithm to merge two sorted arrays into a third array. Do not sort the third array. Q.5 What data structure would you mostly likely see in a non recursive implementation of a recursive algorithm? Q.6 List out the areas in which data structures are applied extensively? Q.7 A two-dimensional array TABLE [6] [8] is stored in row major order with base address 351. What is the address of TABLE [3] [4]? Q.8 How do you find the complexity of an algorithm? What is the relation between the time and space complexities of an algorithm? Justify your answer with an example. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 128 Daily Quiz
  • 129. Question 1: Print Elements of a Matrix in Spiral Order Write a program that reads an MxN matrix A and prints its elements in spiral order. You should start from the element in the 0th row and 0th column in the matrix and proceed in a spiral order as shown below. Output for the above matrix: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Question 2: Write a program that reads an NxN square matrix M that calculates the sum of the elements in individual rows, individual columns and the two main diagonals. Among these sums, print the largest. Consider the following matrix of order 3x3: 1 10 13 2 14 12 3 9 8 The row sum values are 1+10+13=24, 2+14+12=28 and 3+9+8=20. The column sum values are 1+2+3=6, 10+14+9=33 and 13+12+8=33. The diagonal sums are 1+14+8=23 and 13+14+3=30. The expected output is maximum among these sums, which is 33. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 129 Weekly Assignment
  • 130. Question 1: Print Elements of a Matrix in Spiral Order Write a program that reads an MxN matrix A and prints its elements in spiral order. You should start from the element in the 0th row and 0th column in the matrix and proceed in a spiral order as shown below. Output for the above matrix: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Question 2: Write a program that reads an NxN square matrix M that calculates the sum of the elements in individual rows, individual columns and the two main diagonals. Among these sums, print the largest. Consider the following matrix of order 3x3: 1 10 13 2 14 12 3 9 8 The row sum values are 1+10+13=24, 2+14+12=28 and 3+9+8=20. The column sum values are 1+2+3=6, 10+14+9=33 and 13+12+8=33. The diagonal sums are 1+14+8=23 and 13+14+3=30. The expected output is maximum among these sums, which is 33. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 130 Weekly Assignment
  • 131. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 131 Weekly Assignment Question 3: Write a program in C to count a total number of duplicate elements in an array. Test Data : Input the number of elements to be stored in the array :3 Input 3 elements in the array : element - 0 : 5 element - 1 : 1 element - 2 : 1 Expected Output : Total number of duplicate elements found in the array is : 1 Question 4.Write a program in C to merge two arrays of same size sorted in decending order. Test Data : Input the number of elements to be stored in the first array :3 Input 3 elements in the array : element - 0 : 1 element - 1 : 2 element - 2 : 3 Input the number of elements to be stored in the second array :3 Input 3 elements in the array : element - 0 : 1 element - 1 : 2 element - 2 : 3
  • 132. 1. In ........, search start at the beginning of the list and check every element in the list. a. Binary search b. Hash Search c. Linear search d. Binary Tree search. 2. To represent hierarchical relationship between elements, which data structure is suitable? a. Graph b. Tree c. Dequeue d. Priority Queue 3. Which of the following data structure is linear type? a. Stack b. Graph c. Trees d. Binary tree 4.Which of the following data structure can’t store the nonhomogeneous data elements? a. Arrays b. Stacks c. Records d. None of the above 7/4/2020 Megha Gupta KCS 301: DS Unit 1 132 MCQ s
  • 133. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 133 MCQ s 5. Two main measures for the efficiency of an algorithm are a. Processor and memory b. Complexity and capacity c. Time and space d. Data and space 6. The Worst case occur in linear search algorithm when a. Item is somewhere in the middle of the array b. Item is not in the array at all c. Item is the last element in the array d. Item is the last element in the array or is not there at all 7. The complexity of Binary search algorithm is a. O(n) b. O(log ) c. O(n2) d. O(n log n) 8. The complexity of linear search algorithm is a. O(n) b. O(log n) c. O(n2) d. O(n log n)
  • 134. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 134 MCQ s 9. Arrays are best data structures a. for relatively permanent collections of data b. for the size of the structure and the data in the structure are constantly changing c. for both of above situation d. for none of above situation 10. Linked lists are best suited a. for relatively permanent collections of data b. for the size of the structure and the data in the structure are constantly changing c. for both of above situation d. for none of above situation
  • 136. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 136 Expected Questions for University Exam Q1. Assume the declaration of multi-dimensional arrays A and B to be, A (-2:2, 2:22) and B (1:8, -5:5, -10:5) (i) Find the length of each dimension and number of elements in A and B. (ii) Find the address of element B (2, 2, 3), assuming Base address of B = 400 and there are W=4 words per memory location. Q2. Write a program to insert a new element in the given unsorted array at kth position. Q3. Define data structure? What are the factors that influence the choice of particular data structure? Q4 . A 2 dimensional array DATA [-100:100,-5:50] is stored row major order with base address 10. Calculate the address of DATA [99][49]. Q5 Explain Binary search and its limitations. Q6 Write the difference between Linked list and array.
  • 137. Introduction to List and LinkedLists • List is a term used to refer to a linear collection of data items. A List can be implemented either by using arrays or linked lists. • Usually, a large block of memory is occupied by an array which may not be in use and it is difficult to increase the size of an array. • Another way of storing a list is to have each element in a list contain a field called a Linked or pointer, which contains the address of the next element in the list. • The successive elements in the list need not occupy adjacent space in memory. This type of data structure is called a linked list. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 137 Introduction to Linked List
  • 138. What are Linked Lists A linked list is a lineardata structure. Nodes make up linkedlists. Nodes are structures made up of data and a pointer to another node. Usually the pointer iscalled next. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 138 Introduction to Linked List
  • 139. Linked List • It is the most commonly used data structure used to store similar type of data in memory. • The elements of a linked list are not stored in adjacent memory locations as in arrays. • It is a linear collection of data elements, called nodes, where the linear order is implemented by means of pointers. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 139 Introduction to Linked List
  • 140. Linked List • In a linear or single-linked list, a node is connected to the next node by a single Linked. • A node in this type of linked list contains two types of fields • data: which holds a list element • next: which stores a Linked (i.e. pointer) to the next node in the list. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 140 Introduction to Linked List
  • 141. Linked List • The structure defined for a single linked list is implemented as follows: struct Node{ int info; structNode * next; } • The structure declared for linear linked list holds two members • An integer type variable ‘data’ which holds the elements and • Another type ‘node’, which has next, which stores the address of the next node in the list. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 141 Introduction to Linked List
  • 142. Figurative Representation 7/4/2020 Megha Gupta KCS 301: DS Unit 1 142 Introduction to Linked List
  • 143. Properties of Linked list • The nodes in a linked list are not stored contiguously in the memory • You don’t have to shift any element in the list • Memory for each node can be allocated dynamically whenever the need arises. • The size of a linked list can grow or shrink dynamically 7/4/2020 Megha Gupta KCS 301: DS Unit 1 143 Introduction to Linked List
  • 144. Operations on Linked List • Creation: • This operation is used to create a linked list • Insertion / Deletion: • At/From the beginning of the linked list • At/From the end of the linked list • At/From the specified position in a linked list • Traversing: • Traversing may be either forward or backward • Searching: • Finding an element in a linked list • Concatenation: • The process of appending second list to the end of the first list 7/4/2020 Megha Gupta KCS 301: DS Unit 1 144 Introduction to Linked List
  • 145. Arrays Vs Linked Lists Arrays Linked list Fixed size: Resizing is expensive Dynamic size Insertions and Deletions are inefficient: Elements are usually shifted Insertions and Deletions are efficient: No shifting Random access i.e., efficient indexing No random access Not suitable for operations requiring accessing elements by index such as sorting No memory waste if the array is full or almost full; otherwise may result in much memory waste. Since memory is allocated dynamically(acc. to our need) there is no waste of memory. Sequential access is faster [Reason: Elements in contiguous memory locations] Sequential access is slow [Reason: Elements not in contiguous memory locations] 7/4/2020 Megha Gupta KCS 301: DS Unit 1 145 Linked List
  • 146. Types of Linked List • Singly Linked List • Doubly linked list • Circular linked list • Circular doubly linked list 7/4/2020 Megha Gupta KCS 301: DS Unit 1 146 Introduction to Linked List
  • 147. Singly Linked List • A singly linked list is a dynamic data structure which may grow or shrink, and growing and shrinking depends on the operation made. • In this type of linked list each node contains two fields one is data field which is used to store the data items and another is next field that is used to point the next node in the list. 5 3 8 null next next nextinfo info info 7/4/2020 Megha Gupta KCS 301: DS Unit 1 147 Introduction to Linked List
  • 148. Creating a Linked List • The head pointer is used to create and access unnamed nodes. struct Node{ int info; struct Node* next; }; typedef struct Node NodeType; NodeType* head; head=(NodeType *) malloc (sizeof( NodeType ) ); • The above statement obtains memory to store a node and assigns its address to head which is a pointer variable. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 148 Introduction to Linked List
  • 149. Creating a Node • Tocreate a new node, we use the malloc function to dynamically allocate memory for the new node. • After creating the node, we can store the new item in the node using a pointer to that node. • Note that p is not a node; instead it is a pointer to a node. Nodetype *p; p=(NodeType *) malloc (sizeof( NodeType ) ); p- >info=50; p->next = NULL; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 149 Introduction to Linked List
  • 150. Creating an empty list void createEmptyList(NodeType *head) { head=NULL; } OR SIMPLY NodeType *head =Null; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 150 Introduction to Linked List
  • 151. Inserting an Element • While inserting an element or a node in a linked list, we have to do following things: • Allocate a node • Assign a data to info field of the node. • Adjust a pointer • We can insert an element in following places • At the beginning of the linked list • At the end of the linked list • At the specified position in a linked list 7/4/2020 Megha Gupta KCS 301: DS Unit 1 151 Introduction to Linked List
  • 152. An algorithm to insert a node at the beginning of the singly linked list Let *head be the pointer to first node in the current list 1. Create a new node using mallocfunction NewNode=(NodeType*)malloc(sizeof(Node Type)); 2. Assign data to the info field of newnode NewNode->info=newItem; 3. Set next of new node tohead NewNode->next=head; 4. Set the head pointer to the newnode head=NewNode; 5. End 7/4/2020 Megha Gupta KCS 301: DS Unit 1 152 Introduction to Linked List
  • 153. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 153 Introduction to Linked List Insert A Node At The Beginning Of The Singly Linked List
  • 154. Inserting a node at the beginning of the singly linkedlist 7/4/2020 Megha Gupta KCS 301: DS Unit 1 154 Introduction to Linked List
  • 155. An algorithm to insert a node at the end of the singly linked list let *head be the pointer to first node in the current list 1. Create a new node using mallocfunction NewNode=(NodeType*)malloc(sizeof(NodeType)); 2. Assign data to the info field of newnode NewNode->info=newItem; 3. Set next of new node toNULL NewNode->next=NULL; 4. if (head ==NULL) then Set head =NewNode.and exit. 5. Set temp=head; 6. while(temp->next!=NULL) temp=temp->next; //increment temp 7. Set temp->next=NewNode; 8. End 7/4/2020 Megha Gupta KCS 301: DS Unit 1 155 Introduction to Linked List
  • 156. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 156 An algorithm to insert a node at the end of the singly linked list Introduction to Linked List
  • 157. An algorithm to insert a node after the given node in singly linked list let *head be the pointer to first node in the current list and *p be the pointer to the node after which we want to insert a new node. 1. Create a new node using mallocfunction NewNode=(NodeType*)malloc(sizeof(NodeType)); 2. Assign data to the info field of newnode NewNode->info=newItem; 3. Set next of new node to next ofp NewNode->next=p->next; 4. Set next of p to NewNode p->next =NewNode 5. End 7/4/2020 Megha Gupta KCS 301: DS Unit 1 157 Introduction to Linked List
  • 158. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 158 Introduction to Linked List
  • 159. An algorithm to insert a node at the specified position in a linked list let *head be the pointer to first node in the current list 1. Create a new node using mallocfunction NewNode=(NodeType*)malloc(sizeof(NodeType)); 2. Assign data to the info field of new node NewNode->info=newItem; 3. Enter position of a node at which you want to insert a new node. Let this position is pos. 4. Set temp=head; 5. if (head ==NULL)then printf(“void insertion”); and exit(1). 6. for(i=1; i<pos; i++) temp=temp->next; 7. Set NewNode->next=temp->next; set temp->next =NewNode.. 8. End 7/4/2020 Megha Gupta KCS 301: DS Unit 1 159 Introduction to Linked List
  • 160. Deleting Nodes • A node may be deleted: • From the beginning of the linked list • From the end of the linked list • From the specified position in a linked list 7/4/2020 Megha Gupta KCS 301: DS Unit 1 160 Introduction to Linked List
  • 161. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 161 Deleting Nodes Introduction to Linked List
  • 162. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 162 Introduction to Linked List
  • 163. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 163 Introduction to Linked List
  • 164. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 164 Introduction to Linked List
  • 165. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 165 Introduction to Linked List
  • 166. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 166 Introduction to Linked List
  • 167. Searching an item in a linkedlist • Let *head be the pointer to first node in the current list 1. If head==Null Print “Empty List” 2. Else, enter an item to be searched askey 3. Set temp==head 4. While temp!=Null If (temp->info == key) Print “search success” temp=temp->next; 5. If temp==Null Print “Unsuccessful search” 7/4/2020 Megha Gupta KCS 301: DS Unit 1 167 Introduction to Linked List
  • 168. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 168 Introduction to Linked List
  • 169. What is circular linked list? • Circular linked list is a variation of linked list in which the first elements points to the next element and the last element points to the first element. • Both singly and doubly linked list can be made into a circular linked list. • Circular linked list can be used to help traverse the same list again and again if needed. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 169 Circular Linked List
  • 170. Fun fact: If you are worried about its implementation, then stop doing that because instead of placing NULL at the last node’s address field you are placing the address of very first node! 7/4/2020 Megha Gupta KCS 301: DS Unit 1 170 Circular Linked List
  • 171. Circular linked list vs. Linear linked list • A circularly linked list may be a natural option to represent arrays that are naturally circular, e.g. the corners of a polygon, a pool of buffers that are used and released in FIFO order, or a set of processes that should be time-shared. In these applications, a pointer to any node serves as a handle to the whole list. • With a circular list, a pointer to the last node gives easy access also to the first node, by following one Linked. Thus, in applications that require access to both ends of the list, a circular structure allows one to handle the structure by a single pointer, instead of two. • The simplest representation for an empty circular list (when such a thing makes sense) is a null pointer, indicating that the list has no nodes. Without this choice, many algorithms have to test for this special case, and handle it separately. By contrast, the use of null to denote an empty linear list is more natural and often creates fewer special cases. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 171 Circular Linked List
  • 172. Types of circular linked list 1. Singly: The last node points to the first node and there is only Linked between the nodes of linked list. 2. Doubly: The last node points to the first node and there are two links between the nodes of linked list. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 172 Circular Linked List
  • 173. Advantages of Circular linked lists 1. Any node can be a starting point. We can traverse the whole list by starting from any point. We just need to stop when the first visited node is visited again. 2. Circular lists are useful in applications to repeatedly go around the list. For example: when multiple applications are running on a PC, it is common for the operating system to put the running applications on a list and then to cycle through them, giving each of them a slice of time to execute, and then making them wait while the CPU is given to another application. It is convenient for the operating system to use a circular list so that when it reaches the end of the list it can cycle around to the front of the list. 3. Circular Doubly Linked Lists are used for implementation of advanced data structures like Fibonacci Heap. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 173 Circular Linked List
  • 174. Disadvantages of Circular linked list 1. Depending on the implementation, inserting at start of list would require doing a search for last node which could be expensive. 2. Finding end of the list and loop control is harder ( no NULL’s to mark the beginning and end). 7/4/2020 Megha Gupta KCS 301: DS Unit 1 174 Circular Linked List
  • 175. Operations on singly circular linked list • Insertion • Deletion • Display 7/4/2020 Megha Gupta KCS 301: DS Unit 1 175 Circular Linked List
  • 176. Insertion • Insertion can be of three types. ▫ Insert at first ▫ Insert at last ▫ Insert after constant • Note: insertion after constant in circular and linear linked list is exact same . 7/4/2020 Megha Gupta KCS 301: DS Unit 1 176 Circular Linked List
  • 177. Insertion at first 7/4/2020 Megha Gupta KCS 301: DS Unit 1 177 Circular Linked List
  • 178. Algorithm • Start. • Declare struct node *t. • Set t:=start. • Create a new node n by malloc function and enter the information in info part. • Check if start=NULL set start=n set start->next=start. else • Set n->next=start. Program void addfront() { struct node *t=start; struct node *n=(struct node*)malloc(sizeof(struct node)); printf(“nenter the information”); scanf(“%d”,&n- >info); 7/4/2020 Megha Gupta KCS 301: DS Unit 1 178 Circular Linked List
  • 179. Algorithm • Repeat step(a) while(t->next!=start) ▫ (a) set t:=t->next. • [end of loop] • Set t->next=n. • Set start=n. [end if] • Stop. Program if(start==NULL) { start=n; start->next=start; } else { n->next=start; while(t- >next!=start) t=t->next; t->next=n; start=n; } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 179 Circular Linked List
  • 180. Insert at last 7/4/2020 Megha Gupta KCS 301: DS Unit 1 180 Circular Linked List
  • 181. Algorithm • Start. • Declare struct node *t. • Set t:=start. • Create a new node n by malloc function and enter the information in info part. • Check if start=NULL then, set start:=n. set start->next:=start. Otherwise • Set n->next:=start. Program void addlast() { struct node *t=start; struct node *n=(struct node*)malloc(sizeof(struct node)); printf(“nenter the information”); scanf(“%d”,&n- >info); 7/4/2020 Megha Gupta KCS 301: DS Unit 1 181 Circular Linked List
  • 182. Algorithm • Repeat step(a) while(t!=NULL) ▫ (a) set t:=t->next. • [end of loop] • Set t->next=n. [end if] • Stop. Program if(start==NULL) { start=n; start->next=start; } else { n->next=start; while(t!=NULL) t=t- >next; t->next=n; } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 182 Circular Linked List
  • 183. Deletion : • Deletion can be of three types. ▫ Delete from front ▫ Delete from last ▫ Deletion from mid • Note: deletion from mid in circular and linear linked list is exact same . 7/4/2020 Megha Gupta KCS 301: DS Unit 1 183 Circular Linked List
  • 184. Delete from front 7/4/2020 Megha Gupta KCS 301: DS Unit 1 184 Circular Linked List
  • 185. Algorithm start. Check if (start=NULL) then, print “empty list” Check if (start->next=start) then, declare free (t) set start:=NULL otherwise Repeat step(a) while(t- >next!=start) ▫ (a) set t:=t->next [end of loop] void delfront() { struct node *t=start; if (start==NULL) printf (“nempty list”); else if (start->next==start) { free (t); start=NULL; } else { while(t->next!=start){ t=t->next; Program 7/4/2020 Megha Gupta KCS 301: DS Unit 1 185 Circular Linked List
  • 186. set start:=start->next Declare free(t->next). Set t->next:=start. [end of if] stop start=start->next; free(t->next); t->next=start; } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 186 Circular Linked List Continue…
  • 187. Delete from last 7/4/2020 Megha Gupta KCS 301: DS Unit 1 187 Circular Linked List
  • 188. Algorithm • start. • Check if (start=NULL) then, print “empty list” • Check if (start->next=start) then, declare free (t) set start:=NULL otherwise • Repeat step(a) while(t->next->next!=start) ▫ (a) set t:=t->next • [end of loop] • Declare free(t->next). • Set t->next:=start. • [end if] • stop Program void dellast() { struct node *t=start; if (start==NULL) printf(“nempty list”); else if (start->next==start) { free (t); start=NULL ; } else { while(t->next->next!=start) t=t->next; free(t->next); t->next=start; } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 188 Circular Linked List
  • 189. Display 7/4/2020 Megha Gupta KCS 301: DS Unit 1 189 Circular Linked List
  • 190. Algorithm Program • start. • Set struct node *t:=start. • Check if(start=NULL) then, print “empty list” otherwise • Repeat step a and b while(t->next!=start) ▫ (a) print t->info ▫ (b) set t:=t->next • [end of loop] • Print t->info [end if] • stop Void display() { struct node *t=start; if(start=NULL) printf (“nempty list”); else { while(t->next!=start) { printf(“%d”, t->info); t=t->next; } printf(“%d”, t->info); } } 7/4/2020 Megha Gupta KCS 301: DS Unit 1 190 Circular Linked List
  • 191. APPLICATIONS OF LINKED LIST 1.Applications that havean MRU list (a linked list of file names) 2. The cache in your browser that allows you to hit the BACK button (a linked list ofURLs) 3. Undo functionality in Photoshopor Word (a linked list of state) 4. A stack, hash table, and binary tree can be implemented using a doubly linkedlist. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 191 Linked List
  • 192. Doubly Linked List Doubly linked list is a type of linked list in which each node apart from storing its data has two links. The first Linked points to the previous node in the list and the second Linked points to the next node in the list. The first node of the list has its previous Linked pointing to NULL similarly the last node of the list has its next node pointing to NULL. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 192 Linked List The two links help us to traverse the list in both backward and forward direction. But storing an extra Linked requires some extra space.
  • 193. First we define the node. struct node { int data; // Data node *prev; // A reference to the previous node node *next; // A reference to the next node }; 7/4/2020 Megha Gupta KCS 301: DS Unit 1 193 Linked List
  • 194. Important Points to be Remembered In double linked list, the first node must be always pointed by head. Always the previous field of the first node must be NULL. Always the next field of the last node must be NULL 7/4/2020 Megha Gupta KCS 301: DS Unit 1 194 Linked List
  • 195. Operations on Double Linked List In a double linked list, we perform the following operations... 1. Insertion 2. Deletion 3. Display 7/4/2020 Megha Gupta KCS 301: DS Unit 1 195 Linked List
  • 196. Insertion In a double linked list, the insertion operation can be performed in three ways as follows... 1. Inserting At Beginning of the list 2. Inserting At End of the list 3. Inserting At Specific location in the list 7/4/2020 Megha Gupta KCS 301: DS Unit 1 196 Linked List
  • 197. Inserting At Beginning of the list We can use the following steps to insert a new node at beginning of the double linked list... • Step 1 - Create a newNode with given value and newNode → previous as NULL. • Step 2 - Check whether list is Empty (head == NULL) • Step 3 - If it is Empty then, assign NULL to newNode → next and newNode to head. • Step 4 - If it is not Empty then, assign head to newNode → next and newNode to head. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 197 Linked List
  • 198. Inserting At End of the list We can use the following steps to insert a new node at end of the double linked list... • Step 1 - Create a newNode with given value and newNode → next as NULL. • Step 2 - Check whether list is Empty (head == NULL) • Step 3 - If it is Empty, then assign NULL to newNode → previous and newNode to head. • Step 4 - If it is not Empty, then, define a node pointer temp and initialize with head. • Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list (until temp → next is equal to NULL). • Step 6 - Assign newNode to temp → next and temp to newNode → previous. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 198 Linked List
  • 199. Inserting At Specific location in the list (After a Node) We can use the following steps to insert a new node after a node in the double linked list... • Step 1 - Create a newNode with given value. • Step 2 - Check whether list is Empty (head == NULL) • Step 3 - If it is Empty then, assign NULL to both newNode → previous & newNode → next and set newNode to head. • Step 4 - If it is not Empty then, define two node pointers temp1 & temp2 and initialize temp1 with head. • Step 5 - Keep moving the temp1 to its next node until it reaches to the node after which we want to insert the newNode (until temp1 → data is equal to location, here location is the node value after which we want to insert the newNode). • Step 6 - Every time check whether temp1 is reached to the last node. If it is reached to the last node then display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate the function. Otherwise move the temp1 to next node. • Step 7 - Assign temp1 → next to temp2, newNode to temp1 → next, temp1 to newNode → previous, temp2 to newNode → next and newNode to temp2 → previous. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 199 Linked List
  • 200. Deletion In a double linked list, the deletion operation can be performed in three ways as follows... 1. Deleting from Beginning of the list 2. Deleting from End of the list 3. Deleting a Specific Node 7/4/2020 Megha Gupta KCS 301: DS Unit 1 200 Linked List
  • 201. Deleting from Beginning of the list We can use the following steps to delete a node from beginning of the double linked list... • Step 1 - Check whether list is Empty (head == NULL) • Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function. • Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head. • Step 4 - Check whether list is having only one node (temp → previous is equal to temp → next) • Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty list conditions) • Step 6 - If it is FALSE, then assign temp → next to head, NULL to head → previous and delete temp. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 201 Linked List
  • 202. Deleting from End of the list We can use the following steps to delete a node from end of the double linked list... • Step 1 - Check whether list is Empty (head == NULL) • Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not possible' and terminate the function. • Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head. • Step 4 - Check whether list has only one Node (temp → previous and temp → next both are NULL) • Step 5 - If it is TRUE, then assign NULL to head and delete temp. And terminate from the function. (Setting Empty list condition) • Step 6 - If it is FALSE, then keep moving temp until it reaches to the last node in the list. (until temp → next is equal to NULL) • Step 7 - Assign NULL to temp → previous → next and delete temp. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 202 Linked List
  • 203. Deleting a Specific Node from the list We can use the following steps to delete a specific node from the double linked list... • Step 1 - Check whether list is Empty (head == NULL) • Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function. • Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head. • Step 4 - Keep moving the temp until it reaches to the exact node to be deleted or to the last node. • Step 5 - If it is reached to the last node, then display 'Given node not found in the list! Deletion not possible!!!' and terminate the fuction. • Step 6 - If it is reached to the exact node which we want to delete, then check whether list is having only one node or not 7/4/2020 Megha Gupta KCS 301: DS Unit 1 203 Linked List
  • 204. Step 7 - If list has only one node and that is the node which is to be deleted then set head to NULL and delete temp (free(temp)). • Step 8 - If list contains multiple nodes, then check whether temp is the first node in the list (temp == head). • Step 9 - If temp is the first node, then move the head to the next node (head = head → next), set head of previous to NULL (head → previous = NULL) and delete temp. • Step 10 - If temp is not the first node, then check whether it is the last node in the list (temp → next == NULL). • Step 11 - If temp is the last node then set temp of previous of next to NULL (temp → previous → next = NULL) and delete temp (free(temp)). • Step 12 - If temp is not the first node and not the last node, then set temp of previous of next to temp of next (temp → previous → next = temp → next), temp of next of previous to temp of previous (temp → next → previous = temp → previous) and delete temp (free(temp)). 7/4/2020 Megha Gupta KCS 301: DS Unit 1 204 Linked List
  • 205. Displaying a Double Linked List We can use the following steps to display the elements of a double linked list... • Step 1 - Check whether list is Empty (head == NULL) • Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function. • Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head. • Step 4 - Display 'NULL <--- '. • Step 5 - Keep displaying temp → data with an arrow (<===>) until temp reaches to the last node • Step 6 - Finally, display temp → data with arrow pointing to NULL (temp → data ---> NULL). 7/4/2020 Megha Gupta KCS 301: DS Unit 1 205 Linked List
  • 206. • Polynomials 6 2 3 8 0 2 Index represents exponents -3 18 0 0 23 0 42 •Array Implementation: • p1(x) = 8x3 + 3x2 + 2x + 6 • p2(x) = 23x4 + 18x -3 p1(x) p2(x) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 206 Linked List
  • 207. •This is whyarrays aren’tgood to represent polynomials: • p3(x) = 16x21 - 3x5 + 2x +6 6 2 0 0 -3 0 ………… 0 16 WASTE OF SPACE! 7/4/2020 Megha Gupta KCS 301: DS Unit 1 207 Linked List
  • 208. •Advantages of using anArray: • only good for non-sparsepolynomials. • ease of storage andretrieval. •Disadvantages of using anArray: • havetoallocate arraysize ahead of time. • huge array size required for sparse polynomials. Waste of space andruntime. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 208 Linked List
  • 209. • Polynomial Representation • Linked list Implementation: • p1(x) = 23x9 + 18x7 + 41x6 + 163x4 + 3 • p2(x) = 4x6 + 10x4 + 12x + 8 23 9 18 7 41 6 18 7 3 0 4 6 10 4 12 1 8 0 P1 P2 NODE (contains coefficient &exponent) TAIL (contains pointer) 7/4/2020 Megha Gupta KCS 301: DS Unit 1 209 Linked List
  • 210. •Advantages of using a Linkedlist: savespace (don’t have toworryaboutsparse polynomials) and easy to maintain don’t need toallocate list size and can declare nodes (terms) only as needed •Disadvantages of using a Linked list : can’t go backwards through thelist can’t jump to the beginning of the listfrom theend. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 210 Linked List
  • 211. Polynomials A(x) em 1 am 1x am em 2 e0 2 x ... a0 x Representation struct polynode { int coef; int exp; struct polynode * next; }; typedef struct polynode *polyptr; coef exp next 7/4/2020 Megha Gupta KCS 301: DS Unit 1 211 Linked List
  • 212. Adding polynomials using a Linkedlist representation: (storing the result inp3) Todo this, we haveto break the process down to cases: • Case 1: exponent of p1 > exponent ofp2 Copy node of p1 to end ofp3. [go to nextnode] • Case 2: exponent of p1 < exponent ofp2 Copy node of p2 to end ofp3. [go to nextnode] • Case 3: exponent of p1 = exponent ofp2 Create a new node in p3 with the same exponent and with the sum of the coefficients of p1 andp2. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 212 Linked List
  • 213. Example 3 14 2 8 a 8 14 -3 10 b b 1 0 null 10 6 null 8x14 3x10 10x 6 a 3x14 2x8 1 7/4/2020 Megha Gupta KCS 301: DS Unit 1 213 Linked List
  • 214. Adding Polynomials 3 14 a 8 14 2 8 -3 10 1 0 10 6 b 11 14 d a->expon == b->expon 3 14 1 0 a 2 8 -3 10 10 6 b 8 14 11 14 -3 10 a->expon < b->expon 7/4/2020 Megha Gupta KCS 301: DS Unit 1 214 Linked List
  • 215. 3 14 2 8 1 0 a 8 14 -3 10 10 6 b 11 14 -3 10 d a->expon > b->expon 2 8 7/4/2020 Megha Gupta KCS 301: DS Unit 1 215 Linked List
  • 216. Q1. What is the output of following function for start pointing to first node of following linked list? 1->2->3->4->5->6 void fun(struct node* start) { if(start == NULL) return; printf("%d ", start->data); if(start->next != NULL ) fun(start->next->next); printf("%d ", start->data); } Q2. What type of memory allocation is referred for Linked lists? 7/4/2020 Megha Gupta KCS 301: DS Unit 1 216 Daily Quiz
  • 217. Q3. Describe what is Node in Linked list? And name the types of Linked Lists? Q4. Mention what is the difference between Linear Array and Linked List? Q5. Mention what are the applications of Linked Lists? Q6. What does the dummy header in linked list contain? Q7. Mention what is the difference between singly and doubly linked lists? Q8. Mention what is the biggest advantage of linked lists? Q9. Mention how to insert a new node in linked list where free node will be available? 7/4/2020 Megha Gupta KCS 301: DS Unit 1 217 Daily Quiz
  • 218. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 218 Weekly Assignment Q1. Assume that the structure of a Linked List node is as follows: struct node { int data; struct node *next; }; What does the following function print for a given Linked List which has elements in the order 1->2->3->4->5->6. Explain your answer. 1. void fun(struct node* head){ 2. if(head == NULL) 3. return; 4. printf("%d ", head->data); 5. if(head->next != NULL ) 6. fun(head->next->next); 7. printf("%d ", head->data); 8. }
  • 219. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 219 Weekly Assignment Q2. Write a C Program to reverse the Linked list Q3. Write a C Program to merge two Linked list. Q4. Write a C Program to alternate print the content of the list. Q5. Write a program for printing the following in a given linked list: a. Maximum b. Minimum
  • 220. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 220 Weekly Assignment Q6. Print the sum of all even numbers stored in a circular linked list. Q7. Take N numbers as input from the user and create a doubly linked list. Q 8. Find the smallest number in the doubly linked list. Q 9. Delete the smallest number in the doubly linked list. Q 10. Write the C Program to add all even number in the list.
  • 221. 1. What does the following function do for a given Linked List with first node as head? void fun1(struct node* head) { if(head == NULL) return; fun1(head->next); printf("%d ", head->data); } A Prints all nodes of linked lists B Prints all nodes of linked list in reverse order C Prints alternate nodes of Linked List D Prints alternate nodes in reverse order 7/4/2020 Megha Gupta KCS 301: DS Unit 1 221 MCQ s
  • 222. 2. Which of the following points is/are true about Linked List data structure when it is compared with array A Arrays have better cache locality that can make them better in terms of performance. B It is easy to insert and delete elements in Linked List C Random access is not allowed in a typical implementation of Linked Lists D The size of array has to be pre-decided, linked lists can change their size any time. E All of the above 7/4/2020 Megha Gupta KCS 301: DS Unit 1 222 MCQ s
  • 223. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 223 MCQ s 3. Which of the following sorting algorithms can be used to sort a random linked list with minimum time complexity? A Insertion Sort B Quick Sort C Heap Sort D Merge Sort 4. In the worst case, the number of comparisons needed to search a singly linked list of length n for a given element is (GATE CS 2002) A log 2 n B n/2 C log 2 n – 1 D n
  • 224. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 224 MCQ s 5. Is it possible to create a doubly linked list using only one pointer with every node. A Not Possible B Yes, possible by storing XOR of addresses of previous and next nodes. C Yes, possible by storing XOR of current node and next node D Yes, possible by storing XOR of current node and previous node 6. You are given pointers to first and last nodes of a singly linked list, which of the following operations are dependent on the length of the linked list? A Delete the first element B Insert a new element as a first element C Delete the last element of the list D Add a new element at the end of the list
  • 225. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 225 MCQ s 7. Consider the following function to traverse a linked list. void traverse(struct Node *head) { while (head->next != NULL) { printf("%d ", head->data); head = head->next; } } Which of the following is FALSE about above function? A The function may crash when the linked list is empty B The function doesn't print the last node when the linked list is not empty C The function is implemented incorrectly because it changes head
  • 226. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 226 MCQ s 8. Let P be a singly linked list. Let Q be the pointer to an intermediate node x in the list. What is the worst-case time complexity of the best known algorithm to delete the node x from the list? A O(n) B O(log2 n) C O(logn) D O(1) 9. The concatenation of two lists is to be performed in O(1) time. Which of the following implementations of a list should be used? A singly linked list B doubly linked list C circular doubly linked list D array implementation of lists 10. In a doubly linked list, the number of pointers affected for an insertion operation will be A 4 B 0 C 1 D None of these
  • 227. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 227 Expected Questions for University Exam Q1. Write a program in c to delete a specific element in single linked list. Double linked list takes more space than single linked list for storing one extra address. Under what condition, could a double linked list more beneficial than single linked list. Q2. What is a doubly linked list? How is it different from the single linked list? Q3. What are the advantages and disadvantages of array over linked list? Q4 . Write a program to implement linear linked list, showing all the operations that can be performed on a linked list. Q5. Implement Doubly Circular Linked list and insert an element at a given position in the doubly circular Linked list.
  • 229. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 229 Summary Each data structure has strengths and weaknesses which affect performance depending on the task. Arrays allow random access and require less memory per element (do not need space for pointers) while lacking efficiency for insertion/deletion operations and memory allocation. On the contrary, linked lists are dynamic and have faster insertion/deletion time complexities. However, linked list have a slower search time and pointers require additional memory per element in the list.
  • 230. References [1] Aaron M. Tenenbaum, Yedidyah Langsam and Moshe J. Augenstein, “Data Structures Using C and C++”, PHI Learning Private Limited, Delhi India [2] Horowitz and Sahani, “Fundamentals of Data Structures”, Galgotia Publications Pvt Ltd Delhi India. [3] Lipschutz, “Data Structures” Schaum’s Outline Series, Tata McGraw- hill Education (India) Pvt. Ltd. [4] Thareja, “Data Structure Using C” Oxford Higher Education. [5] AK Sharma, “Data Structure Using C”, Pearson Education India. 7/4/2020 Megha Gupta KCS 301: DS Unit 1 230
  • 231. Thank you 7/4/2020 Megha Gupta KCS 301: DS Unit 1 231