0% found this document useful (0 votes)
49 views

Data Structure Unit-1

Uploaded by

NEVER SETTLE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Data Structure Unit-1

Uploaded by

NEVER SETTLE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 125

Noida Institute of Engineering and Technology, Greater Noida

UNIT-1

Unit: 1

Data Structure and Algorithms


Himani Bansal
Assistant Professor
Course Details (CSE)
(B Tech (CSBS) 2nd Sem)

Himani Bansal CSBS (DSA) Unit -1


1
09/14/2021
Content

• Algorithm specification
• Recursion
• Performance analysis
• Asymptotic Notation - The Big-O, Omega and Theta
notation
• Programming Style
• Refinement of Coding - Time-Space Trade Off
• Testing
• Data Abstraction

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 2


Course Objective
• Introduction to basic data structures.

• To know about the basic properties of different data structures.

• Classification and operations on data structure

• Understand algorithms and their efficiency

• Study logical and mathematical description of array and link list.

• Implementation of array and link list on computer.

• Differentiate the usage of array and link list in different scenarios.

Himani Bansal CSBS (DSA) Unit -1


09/14/2021 3
Course Outcome
Bloom’s
CO Description Knowledge
CO Level (KL)
Analyze and implement arrays, linked lists, stacks,
K3, K4
CO1 queues to solve complex problems.

Compare the computational efficiency of the sorting


K4
CO2 and searching algorithms.

Assess the memory representation of tree and


K3
CO3 perform various operations on these data structure.

Apply the concept of recursion to solve the real-world


K3
CO4 problems.

CO5 Develop the algorithms using graph data structures. K6

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 4


CO-PO Mapping
CO-PO correlation matrix of Data Structure and Algorithms (ACSBS 0203)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

ACSBS0203.1 3 3 3 2 - 1 - 1 2 2 2 2

ACSBS0203.2 3 3 2 2 - 1 - 1 2 2 1 2

ACSBS0203.3 3 3 2 2 - 1 - 1 2 2 2 2

ACSBS0203.4 3 3 2 2 - 1 - 1 2 2 2 2

ACSBS0203.5 3 3 3 3 2 2 2 2 3 3 3 3

Average 3 3 2.4 2.2 0.4 1.2 0.4 1.2 2.2 2.2 2 2.2

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 5


Prerequisite and Recap

• Interest
• Get Familiar with programming language ‘C’
• Start learn Data Structure and Algorithm daily.
• Practice ! Because practice makes you perfect.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 6


Unit I Syllabus

Basic Terminologies and Introduction to Algorithm & Data


Organization
Algorithm specification, Recursion, Performance analysis,
Asymptotic Notation - The Big-O, Omega and Theta notation,
Programming Style, Refinement of Coding - Time-Space Trade
Off, Testing, Data Abstraction

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 7


Basic Terminology(CO1)

• Data- values or set of values


• Data item (Group items and Elementary items)
• Entity –something with attributes (properties)
• Entity set
• Information- meaningful or processed data
• Field, records and files

Name Company Engine colour


number
ABC WXYZ XYZ0101 BLACK

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 8


Basic Terminology (contd..)

• The above organization may not be complex enough to maintain


and efficiently process certain collections of data. For this reason,
data are also organized into more complex types of structures. The
study of such structures includes the following three steps:
• Logical or mathematical description.
• Implementation of the structure.
• Quantitative analysis of the structure.
– Memory and time required

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 9


Data Structures(CO1)

• Data may be organized in many different ways; the logical or


mathematical model of a particular organization of data is called a
data structure.
• The choice of a particular data model depends on two
considerations.
– It must be rich enough in structure to mirror the actual
relationships of the data in the real world.
– The structure should be simple enough that one can effectively
process the data when necessary.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 10


Data Structure Operations (CO1)

• Traversing : Accessing each record exactly once


• Searching: Finding the location of the record with a given key value
• Inserting: Adding a new record to the structure.
• Deleting: Removing a record from the structure.
• Sorting: Arranging the records in some logical order
• Merging: Combining the records in two different sorted files into a
single sorted file

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 11


Classification of Data Structures(CO1)

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 12


Algorithm(CO1)

• An algorithm is a finite set of instructions or logic, written in order,


to accomplish a certain predefined task.
• Every Algorithm must satisfy the following properties:
– Input- There should be 0 or more inputs supplied externally to
the algorithm.
– Output- There should be at least 1 output obtained.
– Definiteness- Every step of the algorithm should be clear and
well defined.
– Finiteness- The algorithm should have finite number of steps.
– Correctness- Every step of the algorithm must generate a
correct output.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 13


Efficiency of Algorithm(CO1)

• An algorithm is said to be efficient and fast, if it takes less time to


execute and consumes less memory space

• In order to compare algorithms, we must have some criteria to


measure the efficiency of our algorithms

• The performance of an algorithm is measured on the basis of


following properties :
– Time Complexity
– Space Complexity

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 14


Time and Space Complexity(CO1..)

• Time complexity
– Time Complexity is a way to represent the amount of time
required by the program to run till its completion.
– It's generally a good practice to try to keep the time required
minimum, so that our algorithm completes it's execution in the
minimum time possible.
• Space complexity
– Its the amount of memory space required by the algorithm,
during the course of its execution.
– An algorithm generally requires space for following components
• Instruction Space
• Data Space
• Environment Space

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 15


Asymptotic Notations(CO1)

• Asymptotic analysis of an algorithm refers to defining the


mathematical boundation/framing of its run-time performance.
• Using asymptotic analysis, we can very well conclude the best case,
average case, and worst case scenario of an algorithm.
• Asymptotic analysis is input bound i.e., if there's no input to the
algorithm, it is concluded to work in a constant time. Other than the
"input" all other factors are considered constant.
• Usually, the time required by an algorithm falls under three types −
– Best Case − Minimum time required for program execution.
– Average Case − Average time required for program execution.
– Worst Case − Maximum time required for program execution.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 16


Asymptotic Notations(contd..)

• Following are the commonly used asymptotic notations to calculate


the running time complexity of an algorithm:-
– Ο Notation (Big Oh Notation)
– Ω Notation (Omega Notation)
– θ Notation (Theta Notation)

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 17


Big Oh Notation, Ο

• The notation Ο(n) is the formal way to express the upper bound of
an algorithm's running time. It measures the worst case time
complexity or the longest amount of time an algorithm can possibly
take to complete.

• k=n0
• For example, for a function f(n)
Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all
n > n0. }

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 18


Omega Notation, Ω

• The notation Ω(n) is the formal way to express the lower bound of
an algorithm's running time. It measures the best case time
complexity or the best amount of time an algorithm can possibly
take to complete.

• k=n0
• For example, for a function f(n)
Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all
n > n0. }

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 19


Theta Notation, θ

• The notation θ(n) is the formal way to express both the lower
bound and the upper bound of an algorithm's running time.

• k=n0
• For example, for a function f(n)
θ(f(n)) = { g(n) if and only if g(n) = Ο(f(n)) and g(n) = Ω(f(n)) for all n
> n0 . }
09/14/2021 Himani Bansal CSBS (DSA) Unit -1 20
Common Asymptotic Notations

constant Ο(1)

logarithmic Ο(log n)

linear Ο(n)

n log n Ο(n log n)

quadratic Ο(n2)

cubic Ο(n3)

polynomial nΟ(1)

exponential 2Ο(n)

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 21


Time-space trade-off (CO1)

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


space.
• Also, most people are willing to wait a little while for a big
calculation, but not forever.
• So if your problem is taking a long time but not much memory, a
space-time trade-off would let you use more memory and solve the
problem more quickly.
• Or, if it could be solved very quickly but requires more memory than
you have, you can try to spend more time solving the problem in
the limited memory.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 22


Abstract Data Types (ADT) (CO1)

• The Data Type is basically a type of data that can be used in


different computer program.
• It signifies the type like integer, float etc, the space like integer will
take 4-bytes, character will take 1-byte of space etc.
• The abstract data type is special kind of data type, whose behavior
is defined by a set of values and set of operations.
• The keyword “Abstract” is used as we can use these data types, we
can perform different operations. But how those operations are
working that is totally hidden from the user.
• The ADT is made of with primitive data types, but operation logics
are hidden.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 23


Abstract Data Types (contd..)
• Some examples of ADT are Stack, Queue, List etc.
• Let us see some operations of those mentioned ADT −
• Stack −
– isFull(), This is used to check whether stack is full or not
– isEmpry(), This is used to check whether stack is empty or not
– push(x), This is used to push x into the stack
– pop(), This is used to delete one element from top of the stack
• Queue −
– isFull(), This is used to check whether queue is full or not
– isEmpry(), This is used to check whether queue is empty or not
– insert(x), This is used to add x into the queue at the rear end
– delete(), This is used to delete one element from the front end
of the queue

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 24


Arrays (CO1)

• An array is a collection of variables of the same type that are


referred to through a common name.
• A specific element in an array is accessed by an index.
• In C, all arrays consist of contiguous memory locations.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 25


Array Declaration

• Like other variables, arrays must be explicitly declared so that the


compiler can allocate space for them in memory.
• The general form for declaring a single-dimension array is:
– datatype var_name[size];
• Here, type declares the base type of the array, which is the
type of each element in the array
• size defines how many elements the array will hold.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 26


Array Declaration (Example)

• int marks[10] ;

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 27


Array Initialization

• Let us now see how to initialize an array while declaring it.


• Following are a few examples that demonstrate this.
– int roll[6] = { 2, 4, 12, 5, 45, 5 } ;
– int array[ ] = { 2, 4, 12, 5, 45, 5 } ;
– float points[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
• Note the following points carefully:
– Till the array elements are not given any specific values, they are
supposed to contain garbage values.
– If the array is initialized where it is declared, mentioning the
dimension of the array is optional as in the 2nd example above

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 28


Accessing elements of an Array
• It is done with a subscript, the number in the brackets following the
array name.
• This number specifies the element’s position in the array.
• All the array elements are numbered, starting with 0.
• Thus, marks[2] is not the second element of the array, but the third.
– marks[0] = 1st Array Element
marks[1] = 2nd Array Element
marks[2] = 3rd Array Element
marks[3] = 4th Array Element
marks[4] = 5th Array Element
marks[5] = 6th Array Element
marks[6] = 7th Array Element
marks[7] = 8th Array Element
marks[8] = 9th Array Element
marks[9] = 10th Array Element

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 29


Insertion and Reading data from an array

• Insertion:-Here is the section of code that places data into an array:


– for ( i = 0 ; i <= 10 ; i++ )
{
printf ( " Enter marks: " ) ;
scanf ( "%d", &marks[i] ) ;
}

• Reading:-Access All element using for loop or any other loop


– for ( i = 0 ; i <= 10 ; i++ )
{
printf("%d", marks[i] ) ;
}

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 30


Program to create and display Linear Array
#include<stdio.h>
#include<conio.h>
 void main()
{
int a[50],n,i;
clrscr();
printf("Enter the no. of element in array");
scanf("%d",&n);
printf("\nEnter the elements of the Array(not greater than %d)",n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
 
09/14/2021 Himani Bansal CSBS (DSA) Unit -1 31
Program to create and display Linear Array
(contd..)
printf("\nElements of Array are.");
for(i=1;i<=n;i++)
{
printf("%d ",a[i]);
}
getch();
 }
 Output
 Enter the no. of element in array 10
 Enter the elements of the Array(not greater than 10) 1 2 3 4 5 6 7 89
100 23
 Elements of Array are.1 2 3 4 5 6 7 89 100 23
 
09/14/2021 Himani Bansal CSBS (DSA) Unit -1 32
Multidimensional Array (CO1)

• In C programming, you can create an array of arrays.


• These arrays are known as multidimensional arrays.

• For example,
– float x[3][4];
• Here, x is a two-dimensional (2d) array. The array can hold
12 elements. You can think the array as a table with 3 rows
and each row has 4 columns as shown in figure.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 33


Multidimensional Array

• Similarly, you can declare a three-dimensional (3d) array.


• For example,
– float y[2][4][3];
• Here, the array y can hold 24 elements.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 34


Representation of arrays (CO1)

• A 2D array’s elements are stored in continuous memory locations. It


can be represented in memory using any of the following two ways:

1. Row-Major Order
2. Column-Major Order

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 35


Row-Major Order

• Row Major Order is a method of representing multi dimension array


in sequential memory.
• In this method elements of an array are arranged sequentially row
by row.
• Thus elements of first row occupies first set of memory locations
reserved for the array, elements of second row occupies the next
set of memory and so on.
• Consider a Two Dimensional Array consist of N rows and M
columns. It can be stored sequentially in memory row by row as
shown below:
Row 0 A[0,0] A[0,1] ................. A[0,M-1]
Row 1 A[1,0] A[1,1] ................. A[1,M-1]
  ................................................................
Row N-1 A[N-1,0] A[N-1,1] ................. A[N-1,M-1]
09/14/2021 Himani Bansal CSBS (DSA) Unit -1 36
Row-Major Order

• Example:
Consider following example in which a two dimensional array
consist of two rows and four columns is stored sequentially in row
major order as:

2000 A[0][0]
2002 A[0][1]
Row 0
2004 A[0][2]
2006 A[0][3]
2008 A[1][0]
2010 A[1][1]
Row 1
2012 A[1][2]
2014 A[1][3]

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 37


Row-Major Order

• The Location of element A[i, j] can be obtained by evaluating


expression:
– LOC (A [i, j]) = Base_Address + W [M (i) + (j)]
• Here,
– Base_Address is the address of first element in the array.
– W is the word size. It means number of bytes occupied
by each element.
– N is number of rows in array.
– M is number of columns in array.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 38


Row-Major Order

• Suppose we want to calculate the address of element A [1, 2].


– It can be calculated as follow:
• Here,
Base_Address = 2000, W= 2, M=4, N=2, i=1, j=2
LOC (A [i, j])=Base_Address + W [M (i) + (j)]
LOC (A[1, 2])=2000 + 2 *[4*(1) + 2]
=2000 + 2 * [4 + 2]
=2000 + 2 * 6
=2000 + 12
=2012

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 39


Column Major Order

• Column Major Order is a method of representing multi dimension


array in sequential memory.
In this method elements of an array are arranged sequentially
column by column. Thus elements of first column occupies first set
of memory locations reserved for the array, elements of second
column occupies the next set of memory and so on.
Consider a Two Dimensional Array consist of N rows and M
columns. It can be stored sequentially in memory column by
column as shown below:
Column 0 A[0,0] A[1,0]   A[N-1,0]

Column 1 A[0,1] A[1,1]   A[N-1,1]

   

Column N-1 A[0,M-1] A[1,M-1]   A[N-1,M-1]

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 40


Column Major Order

• Example:
Consider following example in which a two dimensional array
consist of two rows and four columns is stored sequentially in
Column Major Order as:

2000 A[0][0]
Column 0
2002 A[1][0]
2004 A[0][1]
Column 1
2006 A[1][1]
2008 A[0][2]
Column 2
2010 A[1][2]
2012 A[0][3]
Column 3
2014 A[1][3]

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 41


Column Major Order

• The Location of element A[i, j] can be obtained by evaluating


expression:
– LOC (A [i, j]) = Base_Address + W [N (j) + (i)]
• Here,
– Base_Address is the address of first element in the array.
– W is the word size. It means number of bytes occupied
by each element.
– N is number of rows in array.
– M is number of columns in array.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 42


Column Major Order

• Suppose we want to calculate the address of element A [1, 2].


– It can be calculated as follow:
• Here,
Base_Address = 2000, W= 2, M=4, N=2, i=1, j=2
LOC (A [i, j])=Base_Address + W [N (j) + (i)]
LOC (A[1, 2])=2000 + 2 *[2*(2) + 1] 
=2000 + 2 * [4 + 1] 
=2000 + 2 * 5 
=2000 + 10 
=2010

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 43


Application of arrays (CO1)

• 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
– Selection sort
– Quick sort
• Arrays are used to implement Data Structures
– Stack using array
– Queue using array
• Arrays are also used to implement CPU Scheduling Algorithms

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 44


Sparse Matrix (CO1)

• A matrix is a two-dimensional data object made of m rows and n


columns, therefore having total m x n values. If most of the
elements of the matrix have 0 value, then it is called a sparse
matrix.
• Why to use Sparse Matrix instead of simple matrix ?
– Storage: There are lesser non-zero elements than zeros and thus
lesser memory can be used to store only those elements.
– Computing time: Computing time can be saved by logically
designing a data structure traversing only non-zero elements..
– Example
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
09/14/2021 Himani Bansal CSBS (DSA) Unit -1 45
Sparse Matrix Representation

• Representing a sparse matrix by a 2D array leads to wastage of lots


of memory as zeroes in the matrix are of no use in most of the
cases. So, instead of storing zeroes with non-zero elements, we only
store non-zero elements. This means storing non-zero elements
with triples- (Row, Column, value).

• Sparse Matrix Representations can be done in many ways following


are two common representations:
– Array representation
– Linked list representation

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 46


Sparse Matrix Representation

• Method 1: Using Arrays


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

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 47


Sparse Matrix Representation

• Method 2: Using Linked Lists


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

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 48


List

Himani Bansal CSBS (DSA) Unit


09/14/2021 49
-1
Linked Lists (CO1)

• A linked list is a sequence of data structures, which


are connected together via links.
• Linked List is a sequence of links which contains
items. Each link contains a connection to another
link. Linked list is the second most-used data
structure after array.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 50


Linked list
• A linked list consists of:
– A sequence of nodes

a b c d

Each node contains a value


and a link (pointer or reference) to some other node
The last node contains a null link

51
Linked List Representation

• Linked list can be visualized as a chain of nodes, where every node


points to the next node.

• As per the above illustration, following are the important points to


be considered.
– Linked List contains a link element called first/start/head.
– Each link carries a data field(s) and a link field called next.
– Each link is linked with its next link using its next link.
– Last link carries a link as null to mark the end of the list.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 52


Types of Link List

• Following are the various types of linked list.


– Singly Linked List − Item navigation is forward only.
– Doubly Linked List − Items can be navigated forward and
backward.
– Circular Linked List − Last item contains link of the first element
as next
– Circular Doubly Linked List − Last item contains link of the first
element as next and the first element has a link to the last
element as previous. Items can be navigated forward and
backward.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 53


Basic Operations on Linked List

• Following are the basic operations supported by a list.


– Insertion − Adds an element
– Deletion − Deletes an element
– Display/Traversing − Displays the complete list.
– Search − Searches an element using the given key.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 54


Singly Linked List

head

A B C

Himani Bansal CSBS (DSA) Unit


09/14/2021 55
-1
Circular linked list
The pointer from the last element in the list points back
to the first element.

Himani Bansal CSBS (DSA) Unit


09/14/2021 56
-1

Doubly linked list

Himani Bansal CSBS (DSA) Unit


09/14/2021 57
-1
Doubly Circular Linked List

Himani Bansal CSBS (DSA) Unit


09/14/2021 58
-1
Linked list over array
Array contains following limitations:
1. The size of array must be known in advance before
using it in the program.
2. Increasing size of the array is a time taking process. It
is almost impossible to expand the size of the array at
run time.
3. All the elements in the array need to be contiguously
stored in the memory. Inserting any element in the
array needs shifting of all its predecessors.

Himani Bansal CSBS (DSA) Unit


09/14/2021 59
-1
Linked list is useful because

• It allocates the memory dynamically. All the nodes of


linked list are non-contiguously stored in the memory
and linked together with the help of pointers.

• Sizing is no longer a problem since we do not need to


define its size at the time of declaration.
• List grows as per the program's demand and limited
to the available memory space.

Himani Bansal CSBS (DSA) Unit


09/14/2021 60
-1
Singly linked list 
• Singly linked list can be defined as the collection of ordered
set of elements. 
• A node in the singly linked list consist of two parts: data part
and link part.
• Data part of the node stores actual information that is to be
represented by the node.
• The link part of the node stores the address of its immediate
successsor.

Himani Bansal CSBS (DSA) Unit


09/14/2021 61
-1
Operations on Singly Linked List

Himani Bansal CSBS (DSA) Unit


09/14/2021 62
-1
Node Creation
struct node   
{  
    int data;   
    struct node *next;  
};  

struct node *head, *ptr;   

ptr = (struct node *)malloc(sizeof(struct node *));  

Himani Bansal CSBS (DSA) Unit


09/14/2021 63
-1
Insertion
• Insertion at beginning
• Insertion at end of the list
• Insertion after specified node

Himani Bansal CSBS (DSA) Unit


09/14/2021 64
-1
Insertion in singly linked list at beginning
• Allocate the space for the new node and store data into the data part of the node.

ptr = (struct node *) malloc(sizeof(struct node *));  
            ptr → data = item   

• Make the link part of the new node pointing to the existing first node of the list.
ptr->next = head;  

• At the last, we need to make the new node as the first node of the list
head = ptr; 

Himani Bansal CSBS (DSA) Unit


09/14/2021 65
-1
Himani Bansal CSBS (DSA) Unit
09/14/2021 66
-1
Algorithm
• Step 1: IF Avail = NULL
• Write OVERFLOW
     Go to Step 7
   [END OF IF]
• Step 2: SET ptr = avail
• Step 3: SET avail = avail → NEXT
• Step 4: SET ptr → DATA = VAL
• Step 5: SET ptr → NEXT = HEAD
• Step 6: SET HEAD = ptr
• Step 7: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 67
-1
#include<stdio.h>   void beginsert(int item)  
#include<stdlib.h>       {  
void beginsert(int);           struct node *ptr = (struct node *)mall
struct node   oc(sizeof(struct node *));  
{           if(ptr == NULL)  
    int data;           {  
    struct node *next;               printf("\nOVERFLOW\n");  
};           }  
struct node *head;           else  
void main ()           {  
{               ptr->data = item;  
    int choice,item;               ptr->next = head;  
    do                head = ptr;  
    {               printf("\nNode inserted\n");  
        printf("\nEnter the item which you w         }  
ant to insert?\n");             
        scanf("%d",&item);       }  
        beginsert(item);  
        printf("\nPress 0 to insert more ?\n");
  
        scanf("%d",&choice);  
    }while(choice == 0);  
}  

Himani Bansal CSBS (DSA) Unit


09/14/2021 68
-1
Insertion in singly linked list at the end
• In order to insert a node at the last, there are two following
scenarios -

1. The node is being added to an empty list


2. The node is being added to the end of the linked list

   

Himani Bansal CSBS (DSA) Unit


09/14/2021 69
-1
In the first case

• The condition (head == NULL) gets satisfied. Hence, we just


need to allocate the space for the node by using malloc
statement in C. Data and the link part of the node are set up by
using the following statements.
ptr->data = item;  
                ptr -> next = NULL;  
• Since, ptr is the only node that will be inserted in the list
hence, we need to make this node pointed by the head pointer
of the list. This will be done by using the following
Statements.
Head = ptr  

Himani Bansal CSBS (DSA) Unit


09/14/2021 70
-1
In the second case
• Algorithm
• Step 1: IF PTR = NULL Write OVERFLOW
    Go to Step 1
   [END OF IF]
• Step 2: SET NEW_NODE = PTR
• Step 3: SET PTR = PTR - > NEXT
• Step 4: SET NEW_NODE -> DATA = item
• Step 5: SET NEW_NODE - > NEXT = NULL
• Step 6: SET Temp = HEAD
• Step 7: Repeat Step 8 while Temp - > NEXT != NULL
• Step 8: SET Temp = Temp -> NEXT
[END OF LOOP]
• Step 9: SET Temp - > NEXT = NEW_NODE
• Step 10: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 71
-1
#include<stdio.h>   void lastinsert(int item)  
#include<stdlib.h>       {  
void lastinsert(int);           struct node *ptr = (struct node*)malloc(
struct node   sizeof(struct node));     
{           struct node *temp;  
    int data;           if(ptr == NULL)  
    struct node *next;           {  
};               printf("\nOVERFLOW");     
struct node *head;           }  
void main ()           else  
{           {  
    int choice,item;               ptr->data = item;  
    do                if(head == NULL)  
    {               {  
        printf("\nEnter the item which you want                 ptr -> next = NULL;  
 to insert?\n");                   head = ptr;  
        scanf("%d",&item);                   printf("\nNode inserted");  
        lastinsert(item);               }  
        printf("\nPress 0 to insert more ?\n");               else  
        scanf("%d",&choice);               {  
    }while(choice == 0);                   temp = head;  
}                   while (temp -> next != NULL)  
                {  
                    temp = temp -> next;  
                }  
                temp->next = ptr;  
                ptr->next = NULL;  
Himani Bansal CSBS                 printf("\nNode inserted");  
(DSA) Unit
09/14/2021 72
-1               
Himani Bansal CSBS (DSA) Unit
09/14/2021 73
-1
Insertion in singly linked list after specified Node
Algorithm

STEP 1:  IF PTR = NULL STEP 9: PTR → NEXT = TEMP →


WRITE OVERFLOW NEXT
    GOTO STEP 12 STEP 10: TEMP → NEXT = PTR
   END OF IF STEP 12: EXIT
STEP 2: SET NEW_NODE = PTR
STEP 3: NEW_NODE → DATA = VAL
STEP 4: SET TEMP = HEAD
STEP 5: SET I = 0
STEP 6: REPEAT STEP 5 AND 6 UNTIL
Temp-> DATA != DATA
STEP 7: TEMP = TEMP → NEXT
STEP 8: IF TEMP = NULL
WRITE "DESIRED NODE NOT PRESENT"
     GOTO STEP 12
    END OF IF
 END OF LOOP

Himani Bansal CSBS (DSA) Unit


09/14/2021 74
-1
#include<stdio.h>   void create(int item)  
#include<stdlib.h>   {  
void randominsert(int);         
void create(int);           struct node *ptr = (struct node *)malloc
struct node   (sizeof(struct node *));  
{           if(ptr == NULL)  
    int data;           {  
    struct node *next;               printf("\nOVERFLOW\n");  
};           }  
struct node *head;           else  
void main ()           {  
{               ptr->data = item;  
    int choice,item,loc;               ptr->next = head;  
    do                head = ptr;  
    {               printf("\nNode inserted\n");  
        printf("\nEnter the item which you want         }  
 to insert?\n");   }  
        scanf("%d",&item);  
        if(head == NULL)  
        {  
            create(item);  
        }  
        else  
        {  
            randominsert(item);  
        }  
        printf("\nPress 0 to insert more ?\n");  
Himani Bansal CSBS (DSA) Unit
09/14/2021
        scanf("%d",&choice);   -1
75
void randominsert(int item)  
    {  
        struct node *ptr = (struct node *) malloc (sizeof(struct node));  
        struct node *temp;  
        int i,loc;  
        if(ptr == NULL)  
        {  
            printf("\nOVERFLOW");  
        }  
        else  
        {  
            printf("Enter the location");  
            scanf("%d",&loc);             
            ptr->data = item;  
            temp=head;  
            for(i=0;i<loc;i++)  
            {  
                temp = temp->next;  
                if(temp == NULL)  
                {  
                    printf("\ncan't insert\n");  
                    return;  
                }  
              
            }  
            ptr ->next = temp ->next;   
            temp ->next = ptr;    Himani Bansal CSBS (DSA) Unit
09/14/2021 76
            printf("\nNode inserted");   -1
Deletion in singly linked list at beginning
Step 1: IF HEAD = NULL
Write UNDERFLOW
     Go to Step 5
    [END OF IF]
Step 2: SET PTR = HEAD
Step 3: SET HEAD = HEAD -> NEXT
Step 4: FREE PTR
Step 5: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 77
-1
#include<stdio.h>   switch(choice)  
#include<stdlib.h>           {  
void create(int);               case 1:  
void begdelete();               printf("\nEnter the item\n");  
struct node               scanf("%d",&item);  
{               create(item);  
    int data;               break;   
    struct node *next;               case 2:  
};               begdelete();  
struct node *head;               break;   
void main ()               case 3:  
{               exit(0);  
    int choice,item;               break;    
    do                default:  
    {               printf("\nPlease enter valid choice\
        printf("\n1.Append List\n2.Delete no n");  
de\n3.Exit\n4.Enter your choice?");           }  
        scanf("%d",&choice);                     
             }while(choice != 3);  
}  

Himani Bansal CSBS (DSA) Unit


09/14/2021 78
-1
void create(int item)   void begdelete()  
    {       {  
        struct node *ptr = (struct node *)mallo         struct node *ptr;  
c(sizeof(struct node *));           if(head == NULL)  
        if(ptr == NULL)           {  
        {               printf("\nList is empty");  
            printf("\nOVERFLOW\n");           }  
        }           else   
        else           {  
        {               ptr = head;  
            ptr->data = item;               head = ptr->next;  
            ptr->next = head;               free(ptr);  
            head = ptr;               printf("\n Node deleted from the be
            printf("\nNode inserted\n");   gining ...");  
        }           }  
               }  
    }  

Himani Bansal CSBS (DSA) Unit


09/14/2021 79
-1
Deletion in singly linked list at the end
There are two scenarios in which, a node is deleted
from the end of the linked list.

1. There is only one node in the list and that needs


to be deleted.
2. There are more than one node in the list and the
last node of the list will be deleted.

Himani Bansal CSBS (DSA) Unit


09/14/2021 80
-1
In the first scenario
The condition head → next = NULL will survive and
therefore, the only node head of the list will be
assigned to null. This will be done by using the
following statements.

ptr = head  
        head = NULL  
        free(ptr)  

Himani Bansal CSBS (DSA) Unit


09/14/2021 81
-1
In the second scenario

Step 1: IF HEAD = NULL


Write UNDERFLOW
   Go to Step 8
  [END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT!= NULL
Step 4: SET PREPTR = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: SET PREPTR -> NEXT = NULL
Step 7: FREE PTR
Step 8: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 82
-1
#include<stdio.h>   switch(choice)  
#include<stdlib.h>           {  
void create(int);               case 1:  
void end_delete();               printf("\nEnter the item\n");  
struct node               scanf("%d",&item);  
{               create(item);  
    int data;               break;   
    struct node *next;               case 2:  
};               end_delete();  
struct node *head;               break;   
void main ()               case 3:  
{               exit(0);  
    int choice,item;               break;    
    do                default:  
    {               printf("\nPlease enter valid choice\
        printf("\n1.Append List\n2.Delete no n");  
de\n3.Exit\n4.Enter your choice?");           }  
        scanf("%d",&choice);                     
    }while(choice != 3);  
}  

Himani Bansal CSBS (DSA) Unit


09/14/2021 83
-1
void create(int item)   void end_delete()  
    {       {  
        struct node *ptr = (struct node          struct node *ptr,*ptr1;  
*)malloc(sizeof(struct node *));           if(head == NULL)  
        if(ptr == NULL)           {  
        {               printf("\nlist is empty");  
            printf("\nOVERFLOW\n");           }  
        }           else if(head -> next == NULL)  
        else           {  
        {               head = NULL;  
            ptr->data = item;               free(head);  
            ptr->next = head;               printf("\nOnly node of the list deleted ...");      
            head = ptr;       }  
            printf("\nNode inserted\n");   else  
        }           {  
                       ptr = head;   
    }               while(ptr->next != NULL)  
                {  
                    ptr1 = ptr;  
                    ptr = ptr ->next;  
                }  
                ptr1->next = NULL;  
                free(ptr);  
                printf("\n Deleted Node from the last ...");  
            }     
        }  
Himani Bansal CSBS (DSA) Unit
09/14/2021 84
-1
Deletion in singly linked list after the specified node 

• TEP 1: IF HEAD = NULL


• WRITE UNDERFLOW
    GOTO STEP 10
   END OF IF
• STEP 2: SET TEMP = HEAD
• STEP 3: SET I = 0
• STEP 4: REPEAT STEP 5 TO 8 UNTIL I<loc
• STEP 5: TEMP1 = TEMP
• STEP 6: TEMP = TEMP → NEXT
• STEP 7: IF TEMP = NULL
• WRITE "DESIRED NODE NOT PRESENT"
    GOTO STEP 12
    END OF IF
• STEP 8: I = I+1
• END OF LOOP
• STEP 9: TEMP1 → NEXT = TEMP → NEXT
• STEP 10: FREE TEMP
• STEP 11: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 85
-1
Himani Bansal CSBS (DSA) Unit
09/14/2021 86
-1
void delete_specified()  
    {  
        struct node *ptr, *ptr1;  
        int loc,i;   
        scanf("%d",&loc);  
        ptr=head;  
        for(i=0;i<loc;i++)  
        {  
            ptr1 = ptr;       
            ptr = ptr->next;  
              
            if(ptr == NULL)  
            {  
          printf("\nThere are less than %d elements in the list..\n",loc);  
                return;  
            }  
        }  
        ptr1 ->next = ptr ->next;  
        free(ptr);  
        printf("\nDeleted %d node ",loc);  
    }     
Himani Bansal CSBS (DSA) Unit
09/14/2021 87
-1
Traversing in singly linked list
STEP 1: SET PTR = HEAD
STEP 2: IF PTR = NULL
    WRITE "EMPTY LIST"
   GOTO STEP 7
  END OF IF
STEP 4: REPEAT STEP 5 AND 6 UNTIL PTR != NULL
STEP 5: PRINT PTR→ DATA
STEP 6: PTR = PTR → NEXT
[END OF LOOP]
STEP 7: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 88
-1
void traverse()  
    {  
        struct node *ptr;     
        ptr = head;   
        if(ptr == NULL)  
        {  
            printf("Empty list..");  
        }  
        else  
        {  
            printf("printing values . . . . .\n");   
            while (ptr!=NULL)  
            {  
                printf("\n%d",ptr->data);  
                ptr = ptr -> next;  
            }  
        }  
     }  

Himani Bansal CSBS (DSA) Unit


09/14/2021 89
-1
Searching in singly linked list

Step 1: SET PTR = HEAD


Step 2: Set I = 0
STEP 3: IF PTR = NULL
   WRITE "EMPTY LIST"
   GOTO STEP 8
  END OF IF
STEP 4: REPEAT STEP 5 TO 7 UNTIL PTR != NULL
STEP 5: if ptr → data = item
write i+1
 End of IF
STEP 6: I = I + 1
STEP 7: PTR = PTR → NEXT
[END OF LOOP]
STEP 8: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 90
-1
void search()     else  
{               {  
    struct node *ptr;                   flag=1;  
    int item,i=0,flag;               }  
    ptr = head;                i++;  
    if(ptr == NULL)               ptr = ptr -> next;  
    {           }  
        printf("\nEmpty List\n");           if(flag==1)  
    }           {  
    else               printf("Item not found\n");  
    {            }  
   printf("\nEnter item which you want to search?\n");        }     
        scanf("%d",&item);             
        while (ptr!=NULL)   }  
        {  
            if(ptr->data == item)  
            {  
                printf("item found at location %d ",i+1);  
                flag=0;  
            }   
          

Himani Bansal CSBS (DSA) Unit


09/14/2021 91
-1
Doubly linked list

struct node   
{  
    struct node *prev;   
    int data;  
    struct node *next;   
}   

Himani Bansal CSBS (DSA) Unit


09/14/2021 92
-1
Memory Representation of a doubly linked list

Himani Bansal CSBS (DSA) Unit


09/14/2021 93
-1
Insertion in doubly linked list at beginning
There are two scenarios of inserting any element into doubly linked
list. Either the list is empty or it contains at least one element. 

Algorithm :
Step 1: IF ptr = NULL
   Write OVERFLOW
  Go to Step 9
  [END OF IF]
Step 2: SET NEW_NODE = ptr
Step 3: SET ptr = ptr -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> PREV = NULL
Step 6: SET NEW_NODE -> NEXT = HEAD
Step 7: SET head -> PREV = NEW_NODE
Step 8: SET head = NEW_NODE
Step 9: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 94
-1
void insertbeginning(int item)      else   
{      {  
           ptr->data=item;  
   struct node *ptr = (struct node *)malloc(        ptr->prev=NULL;  
sizeof(struct node));          ptr->next = head;  
   if(ptr == NULL)          head->prev=ptr;  
   {          head=ptr;  
       printf("\nOVERFLOW");      }  
   }   }  
   else        
   {   }  
      
      
   if(head==NULL)  
   {  
       ptr->next = NULL;  
       ptr->prev=NULL;  
       ptr->data=item;  
       head=ptr;  
   }  

Himani Bansal CSBS (DSA) Unit


09/14/2021 95
-1
Insertion in doubly linked list at the end
• Step 1: IF PTR = NULL
•   Write OVERFLOW
   Go to Step 11
 [END OF IF]
• Step 2: SET NEW_NODE = PTR
• Step 3: SET PTR = PTR -> NEXT
• Step 4: SET NEW_NODE -> DATA = VAL
• Step 5: SET NEW_NODE -> NEXT = NULL
• Step 6: SET TEMP = START
• Step 7: Repeat Step 8 while TEMP -> NEXT != NULL
• Step 8: SET TEMP = TEMP -> NEXT
• [END OF LOOP]
• Step 9: SET TEMP -> NEXT = NEW_NODE
• Step 10: SET NEW_NODE -> PREV = TEMP
• Step 11: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 96
-1
Himani Bansal CSBS (DSA) Unit
09/14/2021 97
-1
void insertlast(int item)   else  
{          {  
               temp = head;  
   struct node *ptr = (struct node *) malloc           while(temp->next!=NULL)  
(sizeof(struct node));             {  
   struct node *temp;                 temp = temp->next;  
   if(ptr == NULL)             }  
   {             temp->next = ptr;  
       printf("\nOVERFLOW");             ptr ->prev=temp;  
                     ptr->next = NULL;  
   }          }  
   else   printf("\nNode Inserted\n");  
   {                
           }  
        ptr->data=item;   }  
       if(head == NULL)  
       {  
           ptr->next = NULL;  
           ptr->prev = NULL;  
           head = ptr;  
       }  
       

Himani Bansal CSBS (DSA) Unit


09/14/2021 98
-1
Insertion in doubly linked list after Specified node
• Step 1: IF PTR = NULL
•    Write OVERFLOW
   Go to Step 15
 [END OF IF]
• Step 2: SET NEW_NODE = PTR
• Step 3: SET PTR = PTR -> NEXT
• Step 4: SET NEW_NODE -> DATA = VAL
• Step 5: SET TEMP = START
• Step 6: SET I = 0
• Step 7: REPEAT 8 to 10 until I<=LOC
• Step 8: SET TEMP = TEMP -> NEXT
• STEP 9: IF TEMP = NULL
• STEP 10: WRITE "LESS THAN DESIRED NO. OF ELEMENTS"
•    GOTO STEP 15
   [END OF IF]
 [END OF LOOP]
• Step 11: SET NEW_NODE -> NEXT = TEMP -> NEXT
• Step 12: SET NEW_NODE -> PREV = TEMP
• Step 13: SET TEMP -> NEXT -> PREV = NEW_NODE
• Step 14 : SET TEMP -> NEXT = NEW_NODE
• Step 15: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 99
-1
Himani Bansal CSBS (DSA) Unit
09/14/2021 100
-1
void insert_specified(int item)    for(i=0;i<loc;i++)  
{          {  
                 temp = temp->next;  
   struct node *ptr = (struct node *)malloc(            if(temp == NULL)  
sizeof(struct node));              {  
   struct node *temp;                   printf("\ncan't insert\n");  
   int i, loc;                   return;  
   if(ptr == NULL)              }  
   {          }  
       printf("\n OVERFLOW");          ptr->data = item;  
   }          ptr->next = temp->next;  
   else          ptr -> prev = temp;  
   {   temp->next->prev=ptr;  
       printf("\nEnter the location\n");  
       scanf("%d",&loc);          temp->next = ptr;  
       temp=head;                 printf("Node Inserted\n");  
          }  
}  

Himani Bansal CSBS (DSA) Unit


09/14/2021 101
-1
Deletion at beginning
STEP 1: IF HEAD = NULL
WRITE UNDERFLOW
GOTO STEP 6
STEP 2: SET PTR = HEAD
STEP 3: SET HEAD = HEAD → NEXT
STEP 4: SET HEAD → PREV = NULL
STEP 5: FREE PTR
STEP 6: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 102
-1
void beginning_delete()  
{  
    struct node *ptr;  
    if(head == NULL)  
    {  
        printf("\n UNDERFLOW\n");  
    }  
    else if(head->next == NULL)  
    {  ptr=head
        head = NULL;   
        free(ptr);  
        printf("\nNode Deleted\n");  
    }  
    else  
    {  
        ptr = head;  
        head = head -> next;  
        head -> prev = NULL;  
        free(ptr);  
        printf("\nNode Deleted\n");  
    }  
}  
Himani Bansal CSBS (DSA) Unit
09/14/2021 103
-1
Deletion in doubly linked list at the end
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 7
[END OF IF]
Step 2: SET TEMP = HEAD
Step 3: REPEAT STEP 4 WHILE TEMP->NEXT != NULL
Step 4: SET TEMP = TEMP->NEXT
[END OF LOOP]
Step 5: SET TEMP ->PREV-> NEXT = NULL
Step 6: FREE TEMP
Step 7: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 104
-1
1.void last_delete()  
2.{  
3.    struct node *ptr;  
4.    if(head == NULL)  
5.    {  
6.        printf("\n UNDERFLOW\n");  
7.    }  
8.    else if(head->next == NULL)  
9.    {  
10.
        head = NULL;   
11.
        free(head);  
12.
        printf("\nNode Deleted\n");  
13.
    }  
14.
    else   
15.
    {  
16.
        ptr = head;   
17.
        if(ptr->next != NULL)  
18.
        {  
19.
            ptr = ptr -> next;   
20.
        }  
21.
        ptr -> prev -> next = NULL;   
22.
        free(ptr);  
23.
        printf("\nNode Deleted\n");  
24.
    }  
25.
}  

Himani Bansal CSBS (DSA) Unit


09/14/2021 105
-1
Deletion in doubly linked list after the specified node
Step 1: IF HEAD = NULL
    Write UNDERFLOW
   Go to Step 9
  [END OF IF]
Step 2: SET TEMP = HEAD
Step 3: Repeat Step 4 while TEMP -> DATA != ITEM
Step 4: SET TEMP = TEMP -> NEXT
   [END OF LOOP]
• Step 5: SET PTR = TEMP -> NEXT
• Step 6: SET TEMP -> NEXT = PTR -> NEXT
• Step 7: SET PTR -> NEXT -> PREV = TEMP
• Step 8: FREE PTR
• Step 9: EXIT

Himani Bansal CSBS (DSA) Unit


09/14/2021 106
-1
Himani Bansal CSBS (DSA) Unit
09/14/2021 107
-1
1.void delete_specified( )  
2.{  
3.    struct node *ptr, *temp;   
4.    int val;   
5.    printf("Enter the value");  
6.    scanf("%d",&val);  
7.    temp = head;  
8.    while(temp -> data != val)  
9.    temp = temp -> next;  
10.
    if(temp -> next == NULL)  
11.
    {  
12.
        printf("\nCan't delete\n");  
13.
    }  
14.
    else if(temp -> next -> next == NULL)  
15.
    {  ptr=temp->next
16.
        temp ->next = NULL;  

17. free(ptr)
18.
        printf("\nNode Deleted\n");  
19.
    }  
20.
    else  
21.
    {   
22.
        ptr = temp -> next;  
23.
        temp -> next = ptr -> next;  
24.
        ptr -> next -> prev = temp;  
25.
        free(ptr);  
26.
        printf("\nNode Deleted\n");  
27.
    }     
Himani Bansal CSBS (DSA) Unit
28.
}  
09/14/2021
-1
108
Searching for a specific node

• Step 1: IF HEAD == NULL


•   WRITE "UNDERFLOW"
 GOTO STEP 8
 [END OF IF]
• Step 2: Set PTR = HEAD
• Step 3: Set i = 0
• Step 4: Repeat step 5 to 7 while PTR != NULL
• Step 5: IF PTR → data = item
• return i
[END OF IF]
• Step 6: i = i + 1
• Step 7: PTR = PTR → next
• Step 8: Exit

Himani Bansal CSBS (DSA) Unit


09/14/2021 109
-1
void search()  
{  
    struct node *ptr;  
    int item,i=0,flag;  
    ptr = head;   
    if(ptr == NULL)  
    {  
        printf("\nEmpty List\n");  
    }  
    else  
    {   
        printf("\nEnter item which you want to search?\n");   
        scanf("%d",&item);  
        while (ptr!=NULL)  
        {  
            if(ptr->data == item)  
            {  
                printf("\nitem found at location %d ",i+1);  
                flag=0;  
                break;  
            }   
            else  
            {  
                flag=1;  
            }  
            i++;  
            ptr = ptr -> next;  
        }  
        if(flag==1)  
        {  
            printf("\nItem not found\n");  
        }  
    }     
          
}   Himani Bansal CSBS (DSA) Unit
09/14/2021 110
-1
Traversing in doubly linked list
• Step 1: IF HEAD == NULL
•   WRITE "UNDERFLOW"
 GOTO STEP 6
 [END OF IF]
• Step 2: Set PTR = HEAD
• Step 3: Repeat step 4 and 5 while PTR !=
NULL
• Step 4: Write PTR → data
• Step 5: PTR = PTR → next
• Step 6: Exit
Himani Bansal CSBS (DSA) Unit
09/14/2021 111
-1
int traverse()  
{  
    struct node *ptr;  
    if(head == NULL)  
    {  
        printf("\nEmpty List\n");  
    }  
    else   
    {  
        ptr = head;  
        while(ptr != NULL)  
        {  
            printf("%d\n",ptr->data);  
            ptr=ptr->next;  
        }  
    }  
}   

Himani Bansal CSBS (DSA) Unit


09/14/2021 112
-1
Polynomial Representation (CO1)

• A polynomial p(x) is the expression in variable x which is in the form


(axn + bxn-1 + …. + jx+ k), where a, b, c …., k fall in the category of real
numbers and 'n' is non negative integer, which is called the degree
of polynomial.
• An essential characteristic of the polynomial is that each term in the
polynomial expression consists of two parts:
– one is the coefficient
– other is the exponent
• Example:
– 10x2 + 26x,
• here 10 and 26 are coefficients and 2, 1 is its exponential
value.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 113


Polynomial Representation

• Points to keep in Mind while working with Polynomials:


• The sign of each coefficient and exponent is stored within the
coefficient and the exponent itself
• Additional terms having equal exponent is possible one
• The storage allocation for each term in the polynomial must be
done in ascending and descending order of their exponent

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 114


Polynomial Representation

• Addition of polynomial
• Subtraction of polynomial
• Multiplication of polynomial

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 115


Faculty Video Links, Youtube & NPTEL Video Links and Online
Courses Details

• Self Made Video Link:

• Youtube/other Video Links


• Implementation of link list
– https://www.youtube.com/watch?v=6wXZ_m3SbEs
• Polynomial addition using link list
– https://www.youtube.com/watch?v=V_ZNKu_pUPQ

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 116


Weekly Assignment

• Define data structure and explain types of data structure with


suitable examples
• What are the primitive operations in any data structure
• Explain the asymptotic notations with suitable examples
• Differentiate between space and time complexity of an algorithm
• Write an algorithm for merging two already sorted arrays
• Write an algorithm/program for insert a node at between any
position of a linked list
• Write an algorithm/program to reverse a linked list
• Write an algorithm/program to sort two linked lists
• Write an algorithm/program to add two polynomials by using linked
list
• what are the applications of a single linked list, doubly linked list
and circular linked list
09/14/2021 Himani Bansal CSBS (DSA) Unit -1 117
MCQ s

• Which of these best describes an array?


a) A data structure that shows a hierarchical behaviour
b) Container of objects of similar types
c) Arrays are immutable once initialised
d) Array is not a data structure

• How do you initialize an array in C?


a) int arr[3] = (1,2,3);
b) int arr(3) = {1,2,3};
c) int arr[3] = {1,2,3};
d) int arr(3) = (1,2,3);

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 118


MCQ s

• What are the advantages of arrays?


a) Objects of mixed data types can be stored
b) Elements in an array cannot be sorted
c) Index of first element of an array is 1
d) Easier to store elements of same data type

• Elements in an array are accessed _____________


a) randomly
b) sequentially
c) exponentially
d) logarithmically

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 119


MCQ s

• In linked list each node contain minimum of two fields. One field is
data field to store the data second field is?
A. Pointer to character
B. Pointer to integer
C. Pointer to node
D. Node

• Linked list data structure offers considerable saving in


A. Computational Time
B. Space Utilization
C. Space Utilization and Computational Time
D. None of the mentioned

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 120


Old Question Papers

• http://www.aktuonline.com/papers/btech-cs-3-sem-data-structure
s-kcs301-2020.html
• http://www.aktuonline.com/papers/btech-cs-3-sem-data-structure
s-rcs-305-2018-19.html
• http://www.aktuonline.com/papers/btech-cs-3-sem-data-structure
s-rcs-305-2017-18.html
• http://www.aktuonline.com/papers/btech-cs-3-sem-data-structure
s-using-c-ncs-301-2016-17.html

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 121


Expected Questions for University Exam
• What is doubly linked list? What are its applications? Explain how
an element can be deleted from doubly linked list using C program.
• What are the merits and demerits of array? Given two arrays of
integers in ascending order, develop an algorithm to merge these
arrays to form a third array sorted in ascending order.
• How can you represent a sparse matrix in memory?
• List the various operations on linked list.
• What do you understand by time and space trade off?
• Define the various asymptotic notations. Derive the O-notation for
linear search.
• 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.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 122


Summary
• Knowledge of basic data structures is important for understanding
organization of data.
• Understanding of array and link list is compulsory to implement
other data structures.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 123


References
• Aaron M. Tenenbaum, Yedidyah Langsam and Moshe J. Augenstein,
“Data Structures Using C and C++”, PHI Learning Private Limited,
Delhi India
• Horowitz and Sahani, “Fundamentals of Data Structures”, Galgotia
Publications Pvt Ltd Delhi India.
• Lipschutz, “Data Structures” Schaum’s Outline Series, Tata McGraw-
hill Education (India) Pvt. Ltd.
• Thareja, “Data Structure Using C” Oxford Higher Education.
• AK Sharma, “Data Structure Using C”, Pearson Education India.
• Michael T. Goodrich, Roberto Tamassia, David M. Mount “Data
Structures and Algorithms in C++”, Wiley India.
• . P. S. Deshpandey, “C and Data structure”, Wiley Dreamtech
Publication.

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 124


Thank You

09/14/2021 Himani Bansal CSBS (DSA) Unit -1 125

You might also like