You are on page 1of 124

• List ADT

• Array
• Linked List
• Singly linked lists,
• Doubly linked lists,
• Circular linked lists
• Applications:
 Polynomial Manipulation.
• Stack ADT
• Applications of stack:
 Expression Evaluation, Conversion of Infix to postfix and prefix
expression,
 Tower of Hanoi
• Queue ADT
• Types of Queue:
 Circular Queue,
 Double Ended Queue (deQueue)
 Applications
27/09/2022 BCSE202L 1
Recap
What is data structure?
Classification?
ADT?

27/09/2022 BCSE202L 2
Data Structure
• A data structure is a special format for organizing and storing data.
• General data structure types include arrays, linked lists, stacks, queues, trees,
graphs, and so on.
• is, classified based on the data arrangement and the operations performed?
Yes

27/09/2022 BCSE202L 3
Classification of data structure

Abstract Data Types (ADT)

27/09/2022 BCSE202L 4
Datatype?
• How do you store the data in the memory? / representation of
data
• What are the operations that can be performed on the data?
Example:
int a=7
Representation?

Basic operations : addition, subtraction, multiplication, and division

27/09/2022 BCSE202L 5
Abstract Data Type
• Problem solving with a computer refers to processing data.
• To process data, we need to define the data type and the
operation to be performed on the data
• The definition of the data type and the definition of the operation
to be applied to the data is part of the idea behind an Abstract
Data Type (ADT)

27/09/2022 BCSE202L 6
ADT-Example
• Abstract datatypes are defined by their values and operations.
• Abstract is utilised since we can execute multiple operations with
these datatypes.
• User doesn't know how these operations function.
• ADT uses primitive datatypes but hides operation mechanism.
Example:

Operations: Traversal, Search

Implementation: Static or Dynamic

27/09/2022 BCSE202L 7
ADT in Simple Words
• Definition:
• Is a set of operation
• Mathematical abstraction
• No implementation detail
• Example:
• Lists, stacks, queue, tree, graph are examples of ADT along with their
operations

27/09/2022 BCSE202L 8
List-ADT
Array
Linked List

27/09/2022 BCSE202L 9
List-ADT
List Definition
List is an ordered set of elements

General form of the list is A1, A2,A3…., An


• A1 : first element of list
• An: last element of list
• n: size of list

If elements position is Ai, successor is Ai+1 & predecessor Ai-1

27/09/2022 BCSE202L 10
How to store values in List – memory?

10 20 30 40 50

Arrays Linked List

10 20 30 40 50

27/09/2022 BCSE202L 11
Array- Recap

27/09/2022 BCSE202L 12
Array
• An array is a collection of similar elements. These similar elements
could be all ints, or all floats, or all chars, etc.
• Usually, the array of characters is called a ‘string’, whereas an
array of ints or floats is called simply an array.
• any given array must be of the same type. i.e. we cannot have an
array of 10 numbers, of which 5 are ints and 5 are floats.

Data_type Array_Name[Size_of_an_Array];

27/09/2022 BCSE202L 13
Example- program to find average marks obtained by a class of 30 students in a test

27/09/2022 BCSE202L 14
Arrays
• Array Declaration int marks[30] ;
• Accessing Elements of an Array
• This is done with subscript, the number in the brackets following the array
name.
• In our program we are using the variable i as a subscript to refer to various
elements of the array
• Entering Data into an Array
• The for loop causes the process of asking for and receiving
• Reading Data from an Array
• The for loop causes reading the data one by one

27/09/2022 BCSE202L 15
Point to note
• An array is a collection of similar elements.
• The first element in the array is numbered 0, so the last element is 1 less than
the size of the array.
• An array is also known as a subscripted variable.
• Before using an array, its type and dimension must be declared.
• However big an array its elements are always stored in contiguous memory
locations.

27/09/2022 BCSE202L 16
Array Initialisation
• We can store values in array during program execution. We can
also, initialize an array while declaring it as shown below
Examples:
• int num[6] = { 2, 4, 12, 5, 45, 5 } ;
• int n[ ] = { 2, 4, 12, 5, 45, 5 } ;

27/09/2022 BCSE202L 17
Array Elements in Memory
• int arr[8] ;

• 16 bytes get immediately reserved in memory, 2 bytes each for


the 8 integers

27/09/2022 BCSE202L 18
Bounds Checking
• Example

27/09/2022 BCSE202L 19
Bounds Checking
• In C there is no check to see if the subscript used for an array
exceeds the size of the array.
• Data entered with a subscript exceeding the array size will simply
be placed in memory outside the array; probably on top of other
data, or on the program itself.
• This will lead to unpredictable results, to say the least, and there
will be no error message to warn you that you are going beyond
the array size.
• In some cases, the computer may just hang. Thus, the earlier
example program may turn out to be suicidal.

27/09/2022 BCSE202L 20
2D array
• It is also possible for arrays to have two or more dimensions. The
two-dimensional array is also called a matrix.
Datatype array_name[rows][columns]
Ex: int arr[4][5]

Size = 4*5 = 20 elements

Bytes ? = 20 * 2 = 40 bytes

27/09/2022 BCSE202L 21
2D array - Initialization
• int arr[2][3] = {1,2,3,4,5,6}
• int arr[2][3] = {{1,2,3},{4,5,6}}

Access 2D array

27/09/2022 BCSE202L 22
How to read the values from 2D array
• If 1D array use – single for loop to read the elements from the array.
• Then 2D array ?
- Nested for loop – is used
int arr[2][3] = {{1,2,3},{4,5,6}}
for(i=0;i<2;i++) //Rows
{
for(j=0;i<3;j++)//Columns
{
printf(“%d”,a[i][j])
}
}

27/09/2022 BCSE202L 23
Array – Static and Dynamic
• Static :
• Static array is a fixed length container containing n elements
indexable from [0,n-1].
• Memory created in stack.

• Dynamic :
• Array that dynamically increase its length depending on the
volume of the data
• Memory created in heap.

27/09/2022 BCSE202L 24
List ADT - Array
Array Implementation
First step for creating a List ADT using an array – define the data
and the operations that can be performed on that data.

27/09/2022 BCSE202L 25
List – Array Implementation
Data (How the elements in the List should be?)
• Arrays store same-type elements sequentially.
• This data structure is a large, multiple-block memory chunk.
• These blocks store value belonging to any of type: Integer, Float,
Double, Character, etc. But not in combination.

Data_type Array_Name[Size_of_an_Array];

27/09/2022 BCSE202L 26
List – Array Implementation
Operations (What are the operations that can be performed in List
created using array?)
• Traverse
• Insertion
• Deletion

27/09/2022 BCSE202L 27
Array-Traverse
To access each element (item) stored in the array

27/09/2022 BCSE202L 28
Cost of Accessing an Element-Array
• The element can be accessed using its index value
Array[indexvalue]
• To access the third element, A[2] = 6

O(1)

27/09/2022 BCSE202L 29
Array-Insertion
To Insert an element at a specified position

27/09/2022 BCSE202L 30
Cost of Inserting an Element - Array
Insertion is possible as mentioned below:
• Inserting an Element at the Beginning
• Inserting an Element at the End
• Inserting an Element in Mid

27/09/2022 BCSE202L 31
Cost of Inserting an Element
Inserting an Element at the Beginning

To insert a new element at the beginning of an array, shift the


existing element to the right.
Thus, time complexity is related to list size. O(n)

27/09/2022 BCSE202L 32
Cost of Inserting an Element
Inserting an Element at the End

Using the index, we may insert a new element to an array, if not filled
already with its maximum limit.
Thus, time complexity is related to list size. O(1)

27/09/2022 BCSE202L 33
Cost of Inserting an Element
Inserting an Element at the mid

To insert an element in the exact mid position, should perform n/2 shifts.
To insert an element in some random position, again we perform some n shifts.
Thus, time complexity is related to list size. O(n)

27/09/2022 BCSE202L 34
Array-Deletion
To delete an element from a specified position

27/09/2022 BCSE202L 35
Cost of Removing an Element
• Beginning • Mid/Random

O(n)
O(n)

• End

O(1)

27/09/2022 BCSE202L 36
Array-operation-Time Complexity

27/09/2022 BCSE202L 37
Array – Pros and Cons
• Pros:
• Random access is possible, with the index of the element.
• When you must perform more search operation than that of insert or
delete operation then it’s best to go ahead with an array list.

• Cons:
• Array is often of fixed size, later we should add more elements it is
challenging – memory allocation!
• Size of an array has to be known beforehand so that restrict the further
expansion of list to accommodate more elements.
• Increasing the size of array is possible with dynamic array – however, all
the elements from previous array gets copied to new array sequentially
and this happens every time you try to expand your array size, certainly a
costly operation

27/09/2022 BCSE202L 38
How to address the
challenges of the Array?
Linked List

27/09/2022 BCSE202L 39
List ADT - Linked List

27/09/2022 BCSE202L 40
Linked List
• For a linked list, elements are not stored in an orderly fashion (non-contiguous
memory allocation).
• The linked list is made up of multiple nodes/blocks dispersed in a pool of
memory, and each of these nodes stores two fields: Data and Address/Link

27/09/2022 BCSE202L 41
How to define a data in Linked List?
• In Linked List every data should be represented as node – that are
connected using link pointer.
• Thus, the node has to be represented and the datatype of the
node to be defined as follows,
struct node
{
int data;
struct node *next;
};

27/09/2022 BCSE202L 42
Linked List - Types
• Singly linked list
• Doubly linked list
• Circular linked list

27/09/2022 BCSE202L 43
Singly Linked List
• Successive elements are connected by pointers- next/link.
• Last element points to NULL.
• It can grow or shrink in size during execution of a program.
• It can be made just as long as required.
• It does not waste memory space.

27/09/2022 BCSE202L 44
Singly Linked List
• Keeping track of a linked list:
• Must know the pointer to the first element of the list (called start, head,
etc.).

27/09/2022 BCSE202L 45
Singly Linked List - Operations
The possible operations are
1. Traverse
2. Insertion
3. Deletion

Prior performing operations, node should be created.


• Node Creation
• Define the data type for the node
• Create a node

27/09/2022 BCSE202L 46
Node – Linked List
Example – Creating, initialization, memory allocation

27/09/2022 BCSE202L 47
Node - Creation and Initialization
struct node
Node Creation
{ Every node in the linked list is created using the structure in the C
programming language
The data element is stored in the data field, and the next is a pointer to the
int data; address of the next node.

struct node *next;


};
struct node *head;
struct node *one; Node Initialization

struct node *two;


struct node *three;
27/09/2022 BCSE202L 48
Node - Allocate memory for node
head = malloc(sizeof(struct node))
Memory allocation
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
one->data = 1;
Assign data to node
two->data = 2;
three->data=3;

27/09/2022 BCSE202L 49
Singly Linked List – link?
struct node
{
int data;
struct node *next;
};

27/09/2022 BCSE202L 50
Singly Linked List – link?
int main()
{ 1000
10 NULL
struct node *head = malloc(sizeof(struct node));
head -> data = 10;
head -> next = NULL; 1000
head
struct node *head = malloc(sizeof(struct node));
1000 1000
head -> data = 20;
10 NULL 20 NULL
head -> next = NULL;

return 0;
1000
} head

27/09/2022 BCSE202L 51
Singly Linked List
int main()
{
struct node *head = malloc(sizeof(struct node));
1000 2000
head -> data = 10;
10 NULL 20 NULL
head -> next = NULL;

struct node *temp = malloc(sizeof(struct node)); 2000


1000
temp -> data = 20; head temp
temp -> next = NULL;
1000 2000
head -> next = temp;
10 2000 20 NULL
return 0;
} 1000 2000
head temp

27/09/2022 BCSE202L 52
Example
• Creating and displaying element in the linked list

27/09/2022 BCSE202L 53
Singly Linked List-Operations
1. Traverse
2. Insertion
3. Deletion

27/09/2022 BCSE202L 54
Linked List- Traversing
Display elements

27/09/2022 BCSE202L 55
Singly Linked List - Traverse
What is the only information we have w.r.t linked list?

head

27/09/2022 BCSE202L 56
Singly Linked List – Traversing
• Let us assume that the head points to the first node of the list.
• To traverse the list we do the following
• Follow the pointers.
• Display the contents of the nodes as they are traversed
• Stop when the next pointer points to NULL.

27/09/2022 BCSE202L 57
Singly Linked List - Traverse
• To display an element, should traverse the linked list visiting each
node until the end node (NULL) is reached.

Random access is not possible, always traverse through the head only
• Time complexity : O(n)

27/09/2022 BCSE202L 58
Singly Linked List - Insertion
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list

27/09/2022 BCSE202L 59
Inserting At Beginning of the list
• Illustration

Step 1 Create a newNode with given value.

Step 2 Check whether list is Empty (head == NULL)

Step 3 If it is Empty then, set newNode→next = NULL and head = newNode.

Step 4 If it is Not Empty then, set newNode→next = head and head = newNode.

27/09/2022 BCSE202L 60
Inserting At Beginning of the list
• Example

• Time Complexity : O(1)

27/09/2022 BCSE202L 61
Inserting At End of the list
• Taverse the list from start and reach the last node.
• Make the last node point to the new node.
• Make the new node point to null, marking the end of the list.

27/09/2022 BCSE202L 62
Inserting At End of the 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, set head = newNode.

If it is Not Empty then, define a node pointer temp and initialize


Step 4 with head.

Keep moving the temp to its next node until it reaches to the last
Step 5 node in the list (until temp → next is equal to NULL).

Step 6 Set temp → next = newNode.

27/09/2022 BCSE202L 63
Inserting At End of the list
• Inserting a new node at the end is an O(N) operation.

27/09/2022 BCSE202L 64
Inserting At Specific location in the list
• Reach the desired node after which the new node is to be inserted.
• Make the new node point to the next element of the temp node.
• Make the temp node point to the new node.

27/09/2022 BCSE202L 65
Inserting At Specific location in the 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, set newNode → next = NULL and head = newNode.
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 node after which
we want to insert the newNode (until temp → 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 temp is reached to last node or not. If it is reached to
last node then display 'Given node is not found in the list!!! Insertion not
possible!!!' and terminate the function. Otherwise move the temp to next node.
Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp → next = newNode'

27/09/2022 BCSE202L 66
Inserting At Specific location in the list
• Inserting a new node after some node is an O(N) operation.

27/09/2022 BCSE202L 67
Singly Linked List - Deletion
1. Deletion from Beginning of the list
2. Deletion from End of the list
3. Deletion from Specific location in the list

27/09/2022 BCSE202L 68
Deletion from Beginning of the list

27/09/2022 BCSE202L 69
Deletion from Beginning of the 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 → next == NULL)
Step 5 - If it is TRUE then set head = NULL and
delete temp (Setting Empty list conditions)
Step 6 - If it is FALSE then set head = temp → next, and delete temp.

27/09/2022 BCSE202L 70
Deletion from End of the list

27/09/2022 BCSE202L 71
Deletion from End of the 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 two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.
Step 4 - Check whether list has only one Node (temp1 → next == NULL)
Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate the function.
(Setting Empty list condition)
Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat
the same until it reaches to the last node in the list. (until temp1 → next == NULL)
Step 7 - Finally, Set temp2 → next = NULL and delete temp1.

27/09/2022 BCSE202L 72
Deletion from Specific location in the list

27/09/2022 BCSE202L 73
Deletion from Specific location in the 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 two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.

Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the last
node. And every time set 'temp2 = temp1' before moving the 'temp1' to its next 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 function.

27/09/2022 BCSE202L 74
Deletion from Specific location in the list
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
Step 7 - If list has only one node and that is the node to be deleted, then set head = NULL and
delete temp1 (free(temp1)).
Step 8 - If list contains multiple nodes, then check whether temp1 is the first node in the list (temp1 ==
head).
Step 9 - If temp1 is the first node then move the head to the next node (head = head → next) and
delete temp1.
Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next ==
NULL).
Step 11 - If temp1 is last node then set temp2 → next = NULL and delete temp1 (free(temp1)).
Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 → next and
delete temp1 (free(temp1)).

27/09/2022 BCSE202L 75
Circular Linked List
• A circular linked list is a type of linked list in which the first and the
last nodes are also connected to each other to form a circle.
• There are basically two types of circular linked list:
• 1. Circular Singly Linked List
• Here, the address of the last node consists of the address of the
first node.

27/09/2022 BCSE202L 76
Circular Linked List
• 2. Circular Doubly Linked List

27/09/2022 BCSE202L 77
Represenation of CLL
• Let's see how we can represent a circular linked list on an
algorithm/code. Suppose we have a linked list:

27/09/2022 BCSE202L 78
Represenatation of CLL
• Here, the single node is represented as
struct Node
{
int data;
struct Node * next;
};

27/09/2022 BCSE202L 79
Each struct node has a data item and a pointer to the next struct node.
Now we will create a simple circular linked list with three items to understand how this works.
/* Initialize nodes */
struct node *last;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node)); In the above code, one, two, and three are the nodes with data items 1, 2, and 3 respectively.
three = malloc(sizeof(struct node));
/* Assign data values */
one->data = 1;
two->data = 2;
three->data = 3;
/* Connect nodes */
one->next = two;
two->next = three;
three->next = one;
/* Save address of third node in last */
last = three;

27/09/2022 BCSE202L 80
Circular Linked List
In the above code, one, two, and three are the nodes with data
items 1, 2, and 3 respectively.
• For node one
• next stores the address of two (there is no node before it)
• For node two
• next stores the address of three
• For node three
• next stores NULL (there is no node after it)
• next points to node one

27/09/2022 BCSE202L 81
Insertion on a Circular Linked List
• We can insert elements at 3 different positions of a circular linked
list:
• Insertion at the beginning, Insertion in-between nodes Insertion at the end

27/09/2022 BCSE202L 82
Insertion
• 1. Insertion at the Beginning
• store the address of the current first node in the newNode (i.e.
pointing the newNode to the current first node)
• point the last node to newNode (i.e making newNode as head)

27/09/2022 BCSE202L 83
Insertion
• 2. Insertion in between two nodes
• Let's insert newNode after the first node.
• travel to the node given (let this node be p)
• point the next of newNode to the node next to p
• store the address of newNode at next of p

27/09/2022 BCSE202L 84
Insertion
• 3. Insertion at the end
• store the address of the head node to next of newNode
(making newNode the last node)
• point the current last node to newNode
• make newNode as the last node

27/09/2022 BCSE202L 85
Deletion
• Deletion on a Circular Linked List

Suppose we have a double-linked list with elements 1, 2, and 3.

27/09/2022 BCSE202L 86
Deletion
• 1. If the node to be deleted is the only node
• free the memory occupied by the node
• store NULL in last

27/09/2022 BCSE202L 87
Deletion
• 2. If last node is to be deleted
• find the node before the last node (let it be temp)
• store the address of the node next to the last node in temp
• free the memory of last
• make temp as the last node

27/09/2022 BCSE202L 88
Deletion
• 3. If any other nodes are to be deleted
• travel to the node to be deleted (here we are deleting node 2)
• let the node before node 2 be temp
• store the address of the node next to 2 in temp
• free the memory of 2

27/09/2022 BCSE202L 89
Circular Linked List Complexity

27/09/2022 BCSE202L 90
Circular Linked List?
• Why Circular Linked List?
• The NULL assignment is not required because a node always
points to another node.
• The starting point can be set to any node.
• Traversal from the first node to the last node is quick.

27/09/2022 BCSE202L 91
Circular Linked List Applications
• It is used in multiplayer games to give a chance to each player to
play the game.
• Multiple running applications can be placed in a circular linked list
on an operating system. The os keeps on iterating over these
applications.

27/09/2022 BCSE202L 92
Doubly Linked List

27/09/2022 BCSE202L 93
Doubly Linked List
A doubly linked list is a type of linked list in which each node consists
of 3 components:
1. prev - address of the previous node
2. data - data item
3. next - address of next node

A doubly linked list node

27/09/2022 BCSE202L 94
Representation of Doubly Linked List

Let's see how we can represent a doubly linked list on an


algorithm/code.
Suppose we have a doubly linked list:

27/09/2022 BCSE202L 95
Representation of Doubly Linked List

Here, the single node is represented as

Each struct node has a data item, a pointer to the previous struct
node, and a pointer to the next struct node.

27/09/2022 BCSE202L 96
Representation of Doubly Linked List
Now we will create a simple doubly linked list with three items to understand how this works.
/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Assign data values */
one->data = 1;
two->data = 2;
three->data = 3;
/* Connect nodes */
one->next = two;
one->prev = NULL;
two->next = three;
two->prev = one;
three->next = NULL;
three->prev = two;
/* Save address of first node in head */
head = one;

27/09/2022 BCSE202L 97
Representation of Doubly Linked List

In the above code, one, two, and three are the nodes with data
items 1, 2, and 3 respectively.
For node one: next stores the address
of two and prev stores null (there is no node before it)
For node two: next stores the address of three and prev stores the
address of one
For node three: next stores null (there is no node after it)
and prev stores the address of two.
Note: In the case of the head node, prev points to null, and in the
case of the tail pointer, next points to null. Here, one is a head node
and three is a tail node.

27/09/2022 BCSE202L 98
Representation of Doubly Linked List

Insertion on a Doubly Linked List


Pushing a node to a doubly-linked list is similar to pushing a node to a
linked list, but extra work is required to handle the pointer to the
previous node.
We can insert elements at 3 different positions of a doubly-linked list:
Insertion at the beginning
Insertion in-between nodes
Insertion at the End

27/09/2022 BCSE202L 99
Representation of Doubly Linked List
Suppose we have a double-linked list with elements 1, 2, and 3.

27/09/2022 BCSE202L 100


1. Insertion at the Beginning
Let's add a node with value 6 at the beginning of the doubly linked list we made
above.
1. Create a new node
• allocate memory for newNode
• assign the data to newNode.

27/09/2022 BCSE202L 101


1. Insertion at the Beginning
2. Set prev and next pointers of new node
• point next of newNode to the first node of the doubly linked list
• point prev to null

27/09/2022 BCSE202L 102


1. Insertion at the Beginning
3. Make new node as head node
• Point prev of the first node to newNode (now the previous head is
the second node)
• Point head to newNode

27/09/2022 BCSE202L 103


27/09/2022 BCSE202L 104
Code for Insertion at the Beginning

// insert node at the front


void insertFront(struct Node** head, int data) {
// allocate memory for newNode
struct Node* newNode = new Node;
// assign data to newNode
newNode->data = data;
// point next of newNode to the first node of the doubly linked list
newNode->next = (*head);
// point prev to NULL
newNode->prev = NULL;
// point previous of the first node (now first node is the second node) to newNode
if ((*head) != NULL)
(*head)->prev = newNode;
// head points to newNode
(*head) = newNode; }

27/09/2022 BCSE202L 105


2. Insertion in between two nodes
Let's add a node with value 6 after node with value 1 in the doubly
linked list.
1. Create a new node
 allocate memory for newNode
 assign the data to newNode.

27/09/2022 BCSE202L 106


Insertion in between two nodes

2. Set the next pointer of new node and previous node


• assign the value of next from previous node to
the next of newNode
• assign the address of newNode to the next of previous node

27/09/2022 BCSE202L 107


3. Set the prev pointer of new node and the next node
• assign the value of prev of next node to the prev of newNode
• assign the address of newNode to the prev of next node

27/09/2022 BCSE202L 108


Code for Insertion in between two Nodes
// insert a node after a specific node
void insertAfter(struct Node* prev_node, int data) {
// check if previous node is NULL
if (prev_node == NULL) {
cout << "previous node cannot be NULL";
return; }
// allocate memory for newNode
struct Node* newNode = new Node;
// assign data to newNode
newNode->data = data;
// set next of newNode to next of prev node
newNode->next = prev_node->next;
// set next of prev node to newNode
prev_node->next = newNode;
// set prev of newNode to the previous node
newNode->prev = prev_node;
// set prev of newNode's next to newNode
27/09/2022
if (newNode->next != NULL) BCSE202L 109
3. Insertion at the End
Let's add a node with value 6 at the end of the doubly linked list.
1. Create a new node

27/09/2022 BCSE202L 110


3. Insertion at the End
2. Set prev and next pointers of new node and the previous node
If the linked list is empty, make the newNode as the head node. Otherwise, traverse to the end of the
doubly linked list and

The final doubly linked list looks like this.

27/09/2022 BCSE202L 111


Code for Insertion at the End
// insert a newNode at the end of the list
void insertEnd(struct Node** head, int data) {
// allocate memory for node
struct Node* newNode = new Node;

// assign data to newNode


newNode->data = data;

// assign NULL to next of newNode


newNode->next = NULL;

// store the head node temporarily (for later use)


struct Node* temp = *head;
27/09/2022 BCSE202L 112
Code for Insertion at the End
// if the linked list is empty, make the newNode as head node
if (*head == NULL) {
newNode->prev = NULL;
*head = newNode;
return; }
// if the linked list is not empty, traverse to the end of the linked list
while (temp->next != NULL)
temp = temp->next;
// now, the last node of the linked list is temp point the next of the last node (temp) to
newNode.
temp->next = newNode;
// assign prev of newNode to temp
newNode->prev = temp;
}
27/09/2022 BCSE202L 113
Deletion from a Doubly Linked List
Similar to insertion, we can also delete a node from 3 different
positions of a doubly linked list.
Suppose we have a double-linked list with elements 1, 2, and 3.

27/09/2022 BCSE202L 114


1. Delete the First Node of Doubly Linked List
If the node to be deleted (i.e. del_node) is at the beginning

27/09/2022 BCSE202L 115


Code for Deletion of the First Node

if (*head == del_node)
*head = del_node->next;
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
free(del);

27/09/2022 BCSE202L 116


2. Deletion of the Inner Node
If del_node is an inner node (second node), we must have to reset
the value of next and prev of the nodes before and after
the del_node.
For the node before the del_node (i.e. first node)
Assign the value of next of del_node to the next of the first node.
For the node after the del_node (i.e. third node)
Assign the value of prev of del_node to the prev of the third node.

27/09/2022 BCSE202L 117


2. Deletion of the Inner Node

27/09/2022 BCSE202L 118


Code for Deletion of the Inner Node
if (del_node->next != NULL)
del_node->next->prev = del_node->prev;
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;

27/09/2022 BCSE202L 119


3. Delete the Last Node of Doubly Linked List
In this case, we are deleting the last node with value 3 of the doubly
linked list.
Here, we can simply delete the del_node and make the next of node
before del_node point to NULL.

27/09/2022 BCSE202L 120


Code for Deletionat the End
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
Here, del_node ->next is NULL so del_node->prev->next = NULL.
Note: We can also solve this using the first condition (for the node
before del_node) of the second case (Delete the inner node).

27/09/2022 BCSE202L 121


Doubly Linked List Complexity

27/09/2022 BCSE202L 122


Doubly Linked List Applications
• Redo and undo functionality in software.
• Forward and backward navigation in browsers.
• For navigation systems where forward and backward navigation is
required.

27/09/2022 BCSE202L 123


Difference between SLL and
DLL

27/09/2022 BCSE202L 124

You might also like