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

Data Structure and Algorithm Unit 3

Uploaded by

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

Data Structure and Algorithm Unit 3

Uploaded by

ffrahulbansal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1

Unit-3

Linked Lists

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


2

Data Structure
Data structure is a way of storing and organizing data efficiently such that the required
operations on them can be performed be efficient with respect to time as well as memory.
Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code.
Data structures can be two types: 1. Static Data Structure 2. Dynamic Data Structure

What is a Static Data structure?


In Static data structure the size of the structure is fixed. The content of the data structure can be
modified but without changing the memory space allocated to it.

Example of Static Data Structures: Array

What is Dynamic Data Structure?


In Dynamic data structure the size of the structure is not fixed and can be modified during the
operations performed on it. Dynamic data structures are designed to facilitate change of data
structures in the run time.

Example of Dynamic Data Structures: Linked List

Aspect Static Data Structure Dynamic Data Structure

Memory Memory is allocated at


Memory is allocated at run-time
allocation compile-time

Size is fixed and cannot be


Size Size can be modified during runtime
modified

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


3

Memory Memory utilization may be Memory utilization is efficient as


utilization inefficient memory can be reused

Access time is faster as it is Access time may be slower due to


Access
fixed indexing and pointer usage

Arrays, Stacks, Queues, Trees Lists, Trees (with variable size), Hash
Examples
(with fixed size) tables

Features of Dynamic Data Structures:


There are many features of dynamic data structures. Let’s discuss the most popular of them:
 Dynamic Memory Allocation: Dynamic data structures allocate memory at runtime,
rather than being pre-allocated at compile-time. This memory is stored in the program’s
heap.
 Flexible Memory Usage: Unlike static data structures, the memory used by dynamic data
structures is not limited to a fixed size. It can expand or contract as needed during program
execution.
 Manual Memory Management: The memory allocated to dynamic data structures does
not automatically deallocate when the structure goes out of scope. The programmer is
responsible for manually deallocating this memory, often using functions like free() or
delete(), to avoid memory leaks.
 Non-Contiguous Memory: The memory locations used by dynamic data structures are not
guaranteed to be contiguous. This means additional metadata must be stored to track the
locations of each element within the data structure.

Linked List Data Structure


A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers. In simple words, a linked list
consists of nodes where each node contains a data field and a reference(link) to the next node in
the list.

Types Of Linked Lists:


1. Singly Linked List
Singly linked list is the simplest type of linked list in which every node contains some data and a
pointer to the next node of the same data type.
The node contains a pointer to the next node means that the node stores the address of the next
node in the sequence. A single linked list allows the traversal of data only in one way.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


4

2. Doubly Linked List


A doubly linked list or a two-way linked list is a more complex type of linked list that contains
a pointer to the next as well as the previous node in sequence.
Therefore, it contains three parts of data, a pointer to the next node, and a pointer to
the previous node. This would enable us to traverse the list in the backward direction as well.

3. Circular Linked List


A circular linked list is a type of linked list in which the last node’s next pointer points back to
the first node of the list, creating a circular structure. This design allows for continuous
traversal of the list, as there is no null to end the list.
While traversing a circular linked list, we can begin at any node and traverse the list in any
direction forward and backward until we reach the same node we started. Thus, a circular
linked list has no beginning and no end.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


5

Singly Linked List


It consists of nodes where each node contains a data field and a reference to the next node in the
node. The last node points to null, indicating the end of the list.
In a singly linked list, each node consists of two parts: data and a pointer to the next node. The
data part stores the actual information, while the pointer (or reference) part stores the address of
the next node in the sequence. This structure allows nodes to be dynamically linked together,
forming a chain-like sequence.

In this representation, each box represents a node, with an arrow indicating the link to the next
node. The last node points to NULL, indicating the end of the list.

Operations on Singly Linked List


Traversal in Singly Linked List
Traversal involves visiting each node in the linked list and performing some operation on the
data. A simple traversal function would print or process the data of each node.
Step-by-step approach:
 Initialize a pointer current to the head of the list.
 Use a while loop to iterate through the list until the current pointer reaches NULL.
 Inside the loop, print the data of the current node and move the current pointer to the next
node.

Searching in Singly Linked List


Searching in a Singly Linked List refers to the process of looking for a specific element or value
within the elements of the linked list.
Step-by-step approach:
1. Traverse the Linked List starting from the head.
2. Check if the current node's data matches the target value.
 If a match is found, return true.
3. Otherwise, Move to the next node and repeat steps 2.
4. If the end of the list is reached without finding a match, return false.

Insertion in Singly Linked List


Insertion is a fundamental operation in linked lists that involves adding a new node to the list.
There are several scenarios for insertion:
a. Insertion at the Beginning of Singly Linked List:
Step-by-step approach:
 Create a new node with the given value.
 Set the next pointer of the new node to the current head.
 Move the head to point to the new node.
 Return the new head of the linked list.

b. Insertion at the End of Singly Linked List:


To insert a node at the end of the list, traverse the list until the last node is reached, and then link
the new node to the current last node-
Step-by-step approach:

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


6

 Create a new node with the given value.


 Check if the list is empty:
o If it is, make the new node the head and return.
 Traverse the list until the last node is reached.
 Link the new node to the current last node by setting the last node's next pointer to the new
node.
1
c. Insertion at a Specific Position of the Singly Linked List:
To insert a node at a specific position, traverse the list to the desired position, link the new node
to the next node, and update the links accordingly.
We mainly find the node after which we need to insert the new node. If we encounter a NULL
before reaching that node, it means that the given position is invalid.

Deletion in Singly Linked List


Deletion involves removing a node from the linked list. Similar to insertion, there are different
scenarios for deletion:
a. Deletion at the Beginning of Singly Linked List:
To delete the first node, update the head to point to the second node in the list.
Steps-by-step approach:
 Check if the head is NULL.
o If it is, return NULL (the list is empty).
 Store the current head node in a temporary variable temp.
 Move the head pointer to the next node.
 Delete the temporary node.
 Return the new head of the linked list.

b. Deletion at the End of Singly Linked List:


To delete the last node, traverse the list until the second-to-last node and update its next field to
None.
Step-by-step approach:
 Check if the head is NULL.
o If it is, return NULL (the list is empty).
 Check if the head's next is NULL (only one node in the list).
o If true, delete the head and return NULL.
 Traverse the list to find the second last node (second_last).
 Delete the last node (the node after second_last).
 Set the next pointer of the second last node to NULL.
 Return the head of the linked list.

c. Deletion at a Specific Position of Singly Linked List:


To delete a node at a specific position, traverse the list to the desired position, update the links to
bypass the node to be deleted.
Step-by-step approach:
 Check if the list is empty or the position is invalid, return if so.
 If the head needs to be deleted, update the head and delete the node.
 Traverse to the node before the position to be deleted.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


7

 If the position is out of range, return.


 Store the node to be deleted.
 Update the links to bypass the node.
 Delete the stored node.

Doubly Linked List


A doubly linked list is a data structure that consists of a set of nodes, each of which contains
a value and two pointers, one pointing to the previous node in the list and one pointing to
the next node in the list. This allows for efficient traversal of the list in both directions,
making it suitable for applications where frequent insertions and deletions are required.

Representation of Doubly Linked List in Data Structure


In a data structure, a doubly linked list is represented using nodes that have three fields:
1. Data
2. A pointer to the next node (next)
3. A pointer to the previous node (prev)

Each node in a Doubly Linked List contains the data it holds, a pointer to the next node in
the list, and a pointer to the previous node in the list. By linking these nodes together through
the next and prev pointers, we can traverse the list in both directions (forward and backward),
which is a key feature of a Doubly Linked List.

Operations on Doubly Linked List


Traversal in Doubly Linked List
To Traverse the doubly list, we can use the following steps:
a. Forward Traversal:
 Initialize a pointer to the head of the linked list.
 While the pointer is not null:
o Visit the data at the current node.
o Move the pointer to the next node.
b. Backward Traversal:
 Initialize a pointer to the tail of the linked list.
 While the pointer is not null:
o Visit the data at the current node.
o Move the pointer to the previous node.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


8

Insertion at the Beginning in Doubly Linked List

To insert a new node at the beginning of the doubly list, we can use the following steps:
 Create a new node, say new_node with the given data and set its previous pointer to
null, new_node->prev = NULL.
 Set the next pointer of new_node to current head, new_node->next = head.
 If the linked list is not empty, update the previous pointer of the current head to
new_node, head->prev = new_node.
 Return new_node as the head of the updated linked list.

Insertion at the End of Doubly Linked List

To insert a new node at the end of the doubly linked list, we can use the following steps:
 Allocate memory for a new node and assign the provided value to its data field.
 Initialize the next pointer of the new node to nullptr.
 If the list is empty:
o Set the previous pointer of the new node to nullptr.
o Update the head pointer to point to the new node.
 If the list is not empty:
o Traverse the list starting from the head to reach the last node.
o Set the next pointer of the last node to point to the new node.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


9

o Set the previous pointer of the new node to point to the last node.

Insertion at a Specific Position in Doubly Linked List


To insert a node at a specific Position in doubly linked list, we can use the following steps:

To insert a new node at a specific position,


 If position = 1, create a new node and make it the head of the linked list and return it.
 Otherwise, traverse the list to reach the node at position – 1, say curr.
 If the position is valid, create a new node with given data, say new_node.
 Update the next pointer of new node to the next of current node and prev pointer of new
node to current node, new_node->next = curr->next and new_node->prev = curr.
 Similarly, update next pointer of current node to the new node, curr->next = new_node.
 If the new node is not the last node, update prev pointer of new node’s next to the new
node, new_node->next->prev = new_node.

Deletion at the Beginning of Doubly Linked List

To delete a node at the beginning in doubly linked list, we can use the following steps:
 Check if the list is empty, there is nothing to delete. Return.
 Store the head pointer in a variable, say temp.
 Update the head of linked list to the node next to the current head, head = head->next.
 If the new head is not NULL, update the previous pointer of new head to NULL, head-
>prev = NULL.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


10

Deletion at the End of Doubly Linked List

To delete a node at the end in doubly linked list, we can use the following steps:
 Check if the doubly linked list is empty. If it is empty, then there is nothing to delete.
 If the list is not empty, then move to the last node of the doubly linked list, say curr.
 Update the second-to-last node's next pointer to NULL, curr->prev->next = NULL.
 Free the memory allocated for the node that was deleted.

Deletion at a Specific Position in Doubly Linked List

To delete a node at a specific position in doubly linked list, we can use the following steps:
 Traverse to the node at the specified position, say curr.
 If the position is valid, adjust the pointers to skip the node to be deleted.
o If curr is not the head of the linked list, update the next pointer of the node
before curr to point to the node after curr, curr->prev->next = curr-next.
o If curr is not the last node of the linked list, update the previous pointer of the
node after curr to the node before curr, curr->next->prev = curr->prev.
 Free the memory allocated for the deleted node.

Advantages of Doubly Linked List


 Efficient traversal in both directions: Doubly linked lists allow for efficient traversal of
the list in both directions, making it suitable for applications where frequent insertions and
deletions are required.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


11

 Easy insertion and deletion of nodes: The presence of pointers to both the previous and
next nodes makes it easy to insert or delete nodes from the list, without having to traverse
the entire list.
 Can be used to implement a stack or queue: Doubly linked lists can be used to
implement both stacks and queues, which are common data structures used in
programming.

Disadvantages of Doubly Linked List


 More complex than singly linked lists: Doubly linked lists are more complex than singly
linked lists, as they require additional pointers for each node.
 More memory overhead: Doubly linked lists require more memory overhead than singly
linked lists, as each node stores two pointers instead of one.

Applications of Doubly Linked List


 Implementation of undo and redo functionality in text editors.
 Cache implementation where quick insertion and deletion of elements are required.
 Browser history management to navigate back and forth between visited pages.
 Music player applications to manage playlists and navigate through songs efficiently.

Singly linked list (SLL) Doubly linked list (DLL)

SLL nodes contains 2 field -data field DLL nodes contains 3 fields -data field, a
and next link field. previous link field and a next link field.

In SLL, the traversal can be done In DLL, the traversal can be done using the
using the next node link only. Thus previous node link or the next node link. Thus
traversal is possible in one direction traversal is possible in both directions (forward
only. and backward).

Supports additional operations like insert


before, delete previous, delete current node
Supports lesser number of operations
and delete last in O(1) time. Since it supports
in constant time
delete last, it is used to efficiently implement
Deque.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


12

Singly linked list (SLL) Doubly linked list (DLL)

The SLL occupies less memory than The DLL occupies more memory than SLL as
DLL as it has only 2 fields. it has 3 fields.

Complexity of deletion with a given


Complexity of deletion with a given node is
node is O(n), because the previous
O(1) because the previous node can be
node needs to be known, and traversal
accessed easily
takes O(n)

A singly linked list consumes less


The doubly linked list consumes more memory
memory as compared to the doubly
as compared to the singly linked list.
linked list.

Doubly linked list is implemented more in


Singly linked list is relatively less
libraries due to wider number of operations.
used in practice due to limited number
For example Java LinkedList implements
of operations
Doubly Linked List.

Circular Linked List


A circular linked list is a special type of linked list where all the nodes are connected to form
a circle. Unlike a regular linked list, which ends with a node pointing to NULL, the last node
in a circular linked list points back to the first node. This means that you can keep traversing
the list without ever reaching a NULL value.

Types of Circular Linked Lists


1. Circular Singly Linked List
In Circular Singly Linked List, each node has just one pointer called the “next” pointer. The
next pointer of last node points back to the first node and this results in forming a circle. In
this type of Linked list we can only move through the list in one direction.

2. Circular Doubly Linked List:


In circular doubly linked list, each node has two pointers prev and next, similar to doubly
linked list. The prev pointer points to the previous node and the next points to the next node.
Here, in addition to the last node storing the address of the first node, the first node will also
store the address of the last node.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


13

Insertion in the circular linked list:


1. Insertion in an empty List in the circular linked list
To insert a node in empty circular linked list, creates a new node with the given data, sets its
next pointer to point to itself, and updates the last pointer to reference this new node.

2. Insertion at the beginning in circular linked list


To insert a new node at the beginning of a circular linked list, we first create the new node and
allocate memory for it. If the list is empty (indicated by the last pointer being NULL), we
make the new node point to itself. If the list already contains nodes then we set the new node’s
next pointer to point to the current head of the list (which is last->next), and then update the
last node’s next pointer to point to the new node. This maintains the circular structure of the
list.

3. Insertion at the end in circular linked list


To insert a new node at the end of a circular linked list, we first create the new node and
allocate memory for it. If the list is empty (mean, last or tail pointer being NULL), we
initialize the list with the new node and making it point to itself to form a circular structure. If
the list already contains nodes then we set the new node’s next pointer to point to the current
head (which is tail->next), then update the current tail’s next pointer to point to the new
node. Finally, we update the tail pointer to the new node. This will ensure that the new node
is now the last node in the list while maintaining the circular linkage.

4. Insertion at specific position in circular linked list


To insert a new node at a specific position in a circular linked list, we first check if the list is
empty. If it is and the position is not 1 then we print an error message because the position
doesn’t exist in the list. If the position is 1 then we create the new node and make it point to
itself. If the list is not empty, we create the new node and traverse the list to find the correct
insertion point. If the position is 1, we insert the new node at the beginning by adjusting the
pointers accordingly. For other positions, we traverse through the list until we reach the desired
position and inserting the new node by updating the pointers. If the new node is inserted at the
end, we also update the last pointer to reference the new node, maintaining the circular
structure of the list.

Deletion from a Circular Linked List


Deletion involves removing a node from the linked list. The main difference is that we need to
ensure the list remains circular after the deletion. We can delete a node in a circular linked list
in three ways:

1. Delete the first node in circular linked list


To delete the first node of a circular linked list, we first check if the list is empty. If it is then
we print a message and return NULL. If the list contains only one node (the head is the same
as the last) then we delete that node and set the last pointer to NULL. If there are multiple
nodes then we update the last->next pointer to skip the head node and effectively removing it
from the list. We then delete the head node to free the allocated memory. Finally, we return
the updated last pointer, which still points to the last node in the list.
DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK
14

2. Delete a specific node in circular linked list


To delete a specific node from a circular linked list, we first check if the list is empty. If it is
then we print a message and return nullptr. If the list contains only one node and it matches
the key then we delete that node and set last to nullptr. If the node to be deleted is the first
node then we update the next pointer of the last node to skip the head node and delete the
head. For other nodes, we traverse the list using two pointers: curr (to find the node) and prev
(to keep track of the previous node). If we find the node with the matching key then we update
the next pointer of prev to skip the curr node and delete it. If the node is found and it is the
last node, we update the last pointer accordingly. If the node is not found then do nothing and
tail or last as it is. Finally, we return the updated last pointer.

3. Deletion at the end of Circular linked list


To delete the last node in a circular linked list, we first check if the list is empty. If it is, we
print a message and return nullptr. If the list contains only one node (where the head is the
same as the last), we delete that node and set last to nullptr. For lists with multiple nodes, we
need to traverse the list to find the second last node. We do this by starting from the head and
moving through the list until we reach the node whose next pointer points to last. Once we find
the second last node then we update its next pointer to point back to the head, this effectively
removing the last node from the list. We then delete the last node to free up memory and return
the updated last pointer, which now points to the last node.

Searching in Circular Linked list


Searching in a circular linked list is similar to searching in a regular linked list. We start at a
given node and traverse the list until you either find the target value or return to the starting
node. Since the list is circular, make sure to keep track of where you started to avoid an infinite
loop.
To search for a specific value in a circular linked list, we first check if the list is empty. If it is
then we return false. If the list contains nodes then we start from the head node (which is the
last->next) and traverse the list. We use a pointer curr to iterate through the nodes until we
reach back to the head. During traversal, if we find a node whose data matches the given key
then we return true to indicating that the value was found. After the loop, we also check the
last node to ensure we don’t miss it. If the key is not found after traversing the entire list then
we return false.

Advantages of Circular Linked Lists


 In circular linked list, the last node points to the first node. There are no null references,
making traversal easier and reducing the chances of encountering null pointer exceptions.
 We can traverse the list from any node and return to it without needing to restart from the
head, which is useful in applications requiring a circular iteration.
 Circular linked lists can easily implement circular queues, where the last element connects
back to the first, allowing for efficient resource management.
 In a circular linked list, each node has a reference to the next node in the sequence.
Although it doesn’t have a direct reference to the previous node like a doubly linked list,
we can still find the previous node by traversing the list.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK


15

Disadvantages of Circular Linked Lists


 Circular linked lists are more complex to implement than singly linked lists.
 Traversing a circular linked list without a clear stopping condition can lead to infinite loops
if not handled carefully.
 Debugging can be more challenging due to the circular nature, as traditional methods of
traversing linked lists may not apply.

Applications of Circular Linked Lists


 It is used for time-sharing among different users, typically through a Round-Robin
scheduling mechanism.
 In multiplayer games, a circular linked list can be used to switch between players. After the
last player’s turn, the list cycles back to the first player.
 Circular linked lists are often used in buffering applications, such as streaming data, where
data is continuously produced and consumed.
 In media players, circular linked lists can manage playlists, this allowing users to loop
through songs continuously.

DATA STRUCTURE AND ALGORITHM DIKSHA KAUSHIK

You might also like