0% found this document useful (0 votes)
14 views71 pages

DSA Chapter 3 - Linked Lists -All Parts

Chapter Three of 'Data Structures and Algorithms' by Kibru G. focuses on Linked Lists, detailing their types, applications, and common operations. It explains the structure of linked lists, including singly, doubly, and circular linked lists, and emphasizes the advantages of dynamic data structures over static ones. The chapter also covers basic operations such as insertion, deletion, and traversal of linked lists, providing examples and syntax for implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views71 pages

DSA Chapter 3 - Linked Lists -All Parts

Chapter Three of 'Data Structures and Algorithms' by Kibru G. focuses on Linked Lists, detailing their types, applications, and common operations. It explains the structure of linked lists, including singly, doubly, and circular linked lists, and emphasizes the advantages of dynamic data structures over static ones. The chapter also covers basic operations such as insertion, deletion, and traversal of linked lists, providing examples and syntax for implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Data

Structures
and
Algorithms
C H A P TE R TH R E E :
LIN K E D LIS TS

DATA STRUCTURES AND ALGORITHM BY: KIBRU G.


Outline
▪Introduction to Linked List

▪ Types of Linked List

▪ Singly Linked Lists

▪ Doubly Linked Lists

▪ Circular Linked Lists

▪Applications of Linked Lists

▪Common Problems and Algorithms on Linked Lists

▪Advanced Topics (Reading Assignment)

▪ Skip Lists.

▪ Self-organizing Linked Lists.

▪ XOR Linked Lists (Memory-efficient Doubly Linked List).

▪ Unrolled Linked Lists.


4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 2
Introduction to Linked List
▪Grouping Data: Programming languages provide ways to group related data.
▪Data Organization: Data structures define how data is arranged, ranging from
simple arrays to complex structures.
▪Multiple Choices: Different data structures can serve the same purpose,
requiring careful selection.
▪Link to Algorithms: The choice of data structure affects algorithm efficiency and
complexity.
▪Performance Considerations: Inefficient algorithms may not be feasible for large
datasets.
▪Importance of Selection: Choosing the right data structure is crucial for program
efficiency.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 3
Introduction to Linked List
▪Types of Data Structures: Data structures are classified as static or
dynamic.
▪Static Data Structures: Data structures whose size and memory
allocation are fixed at compile-time.
▪Their form cannot change during execution (e.g., C++ arrays).
▪Size must be known at compile-time.
▪Data is stored in continuous memory, making insertions or deletion
operations in the middle too costly because you are required to shift
other elements, which is inefficient (O(n) time complexity).
▪Wasted memory if the allocated size is larger than needed.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 4
Introduction to Linked List
▪Dynamic Data Structures: Data structures that can grow, shrink, or change their form
during program execution.
▪Example: Linked lists, stacks, queues, trees, graphs.
▪Size can change dynamically as needed.
▪Memory is allocated non-contiguously (nodes can be scattered in memory).
▪Efficient insertion and deletion (O(1) in many cases, e.g., at the head/tail of a linked
list).
▪No need to pre-allocate memory; uses memory only as needed.
▪Flexible and adaptable to complex problems.
▪Slightly higher memory overhead due to storing pointers/references.
▪No random access; sequential access only (e.g., O(n) for accessing an element in a
linked list).
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 5
Introduction to Linked List
▪Why Linked Lists?
▪ Overcome limitations of static data structures like arrays.
▪ Allow dynamic memory allocation and efficient insertion/deletion.
▪Use Cases or when shall we use Linked Lists?
▪ When the size of the data is unknown or changes frequently.
▪ When frequent insertions/deletions are required (e.g., implementing stacks, queues, or
graphs).
▪Key Takeaway:
▪ Static data structures are simple and fast for fixed-size problems but lack flexibility.
▪ Dynamic data structures are powerful tools for solving complex, dynamic problems but
come with trade-offs like higher memory overhead and slower access times.
▪Linked lists are a fundamental example of dynamic data structures, offering flexibility and
efficiency for certain operations.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 6
Introduction to Linked List
▪A linked list is made up of many nodes which are connected in nature.

▪It is a set of nodes where each nodes has two fields:

1.Data field: store the actual piece of information

2.Link field: points to the next node(holds the address of the next
node)

▪A linked list is a data structure which is built from structures and


pointers.

▪It forms a chain of "nodes" with pointers representing the links of the
chain and holding the entire thing together.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 7
Introduction to Linked List

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 8
Introduction to Linked List

Start

▪Name: Abebe Name: Ali


Age: 34
Age: 13
Height: 1.7
Height: 1.3

Name: Sosna Name: Martha


Age: 12 Age: 15
Height: 1.2 Height: 1.4

Null
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 9
Introduction to Linked List
▪This linked list has four nodes in it, each with a link to the
next node in the series.

▪The last node has a link to the special value NULL, which
any pointer (whatever its type) can point to, to show that it
is the last link in the chain.

▪There is also another special pointer, called Start, which


points to the first link in the chain so that we can keep track
of it.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 10
Types of Linked Lists
▪Singly Linear Linked List
▪Consists only one link points to next node
▪Singly Circular Linked List
▪One link is point to next element and this list is circular because the last node
point to first node
▪Doubly Linear Linked List
▪Consists two pointers one point to next node and the other point to previous node
▪Doubly Circular Linked List
▪Previous pointer of the first node and the next pointer of the last node point to
the head node

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 11
Types of Linked Lists
NULL
1 data Link data Link

data Link data Link 2

Link Link
3 data data
Link Link

data data data 4


Link Link Link Link Link Link

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 12
4 Things When Building Linked
List
1. Structure of a Linked List
▪Data Element: This is the actual value or data stored in each node of the linked list. It can
be of any data type (e.g., integer, string, object).
▪Link Field (Pointer): This is a reference (or pointer) to the next node in the list. In a singly
linked list, each node points to the next node. In a doubly linked list, each node points to both
the next and the previous node.

2. The Way to Make Links Between Elements


▪First Element (Head): The first node in the list. It is the entry point to the linked list.
▪Last Element (Tail): The last node in the list. Its next pointer is None (or null in some
languages) to indicate the end of the list.
▪Middle Elements: Nodes between the head and tail. Each node points to the next node in
the sequence.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 13
4 Things When Building Linked
List
3. How Many Nodes to Take All List Elements, How to Traverse the List

▪The number of nodes in the list is equal to the number of elements in the list.

▪To traverse the list, start at the head and follow the next pointers until you reach a node

where next is None.

4. Basic operations:

1. Insertion:

▪At the Beginning: Update the new node’s next to point to the current head, then update

the head to the new node.

▪At the End: Traverse to the last node, then update its next to point to the new node.

▪In the Middle: Traverse to the desired position, update the new node’s next to point to the

next node, and update the previous node’s next to point to the new node.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 14
4 Things When Building Linked
List
4. Basic operations:
2.Deletion:
▪At the Beginning: Update the head to point to the second node.

▪At the End:Traverse to the second-to-last node and set its next to None.

▪In the Middle: Traverse to the node before the one to be deleted, and
update its next to skip the node to be deleted.
3.Search (Find):
▪Traverse the list and compare each node’s data with the target value.
Return the node if found, otherwise return None.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 15
Types of Linked Lists:
Singly Linked Lists
▪ In C++,linked list can be defined using structures and pointers.
▪ Each structure represents a node having some data and also a pointer that holds
the address of the next node and creates the link between two nodes.
▪ Nodes can be located anywhere in memory, as they are connected via links.
▪ The simplest form of linked list is the singly linked list.
▪ In a singly linked list, each node contains some data and a single link to its
successor in the list.

▪ Note that only one variable p can be used to access any node in the list.
▪ The last node in the list is indicated by having a null pointer (backslash ‘\’ symbol
to denotes the null pointer).
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 16
Types of Linked Lists:
Singly Linked Lists: Syntax
struct nodeType {

int info; // stores the actual value


nodeType *link; // Pointer to next node
};
nodeType *head; //*head will permanently
point to the start of the list
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 17
Types of Linked Lists:
Singly Linked Lists: Example
struct node {
char name[20]; // Name of up to 20 chars
int age; // D.O.B. would be better
float height; // In meters
node *link; // Pointer to next node
};
node *head = NULL;
//head will permanently point to the start of the list
▪The key part of a linked list is a structure, which holds the data for each node (the
name, address, age or whatever for the items in the list), and, most importantly, a
pointer to the next node.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 18
Types of Linked Lists:
Singly Linked Lists: Some Properties
▪Consider the linked list with 4 nodes:

▪The address of the first node is stored in the pointer head.


Each node has two components: info, to store the actual data, and link,
to store the address of the next node.
▪The first node is at location 2000, the second node is at location 2800,
the third node is at location 1500, and the fourth node is at location
3600.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 19
Types of Linked Lists:
Singly Linked Lists: Some Properties

▪Suppose that current is a pointer of the same type as the pointer head. Then the
statement
▪current = head; copies the value of head into current.
▪Now consider the following statement:
▪current = current->link; This statement copies the value of current->link, which is
2800, into current.
▪Therefore, after this statement executes, current points to the second node in the list.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 20
Types of Linked Lists:
Singly Linked Lists: Some Properties

▪List after the statement

current = current->link; executes

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 21
Types of Linked Lists:
Singly Linked Lists: Some Properties
▪Values of current, head, and some of the nodes of the linked
list

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 22
Types of Linked Lists:
Singly Linked Lists: Traversal
▪The basic operations of a linked list are as follows:

▪ Search the list to determine whether a particular item is in

the list,

▪ Insert an item in the list, and

▪ Delete an item from the list.

▪These operations require the list to be traversed. That is,


given a pointer to the first node of the list, we must step
through the nodes of the list.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 23
Types of Linked Lists:
Singly Linked Lists: Traversal

▪Suppose that current is a pointer


of the same type as head. The following
code traverses the list:

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 24
Types of Linked Lists:
Singly Linked Lists: Traversal
▪ For example, suppose that head points to a linked list
of numbers.
▪ The following code outputs the data stored in each
node:

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 25
Types of Linked Lists:
Singly Linked Lists: Insertion and Deletion
▪Consider the following definition of a node.

struct nodeType
{
int info;
nodeType *link;
};

//We will use the following variable declaration:


nodeType *head, *p, *q, *newNode;
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 26
Types of Linked Lists:
Singly Linked Lists: Insertion
▪Consider the linked list shown in Figure below፡ before item Insertion:

▪// Function to create a new node:


Node* createNode(int value) {
Node* newNode = new Node();
newNode->info = value;
newNode->next = nullptr;
return newNode;
}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 27
Types of Linked Lists:
Singly Linked Lists: Insertion
▪Suppose that p points to the node with info 65, and a new
node with info 50 is to be created and inserted after p.

▪Consider the following statements:

newNode = new nodeType; //create newNode


newNode->info = 50; //store 50 in the new node

newNode->link = p->link;
p->link = newNode;
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 28
Types of Linked Lists:
Singly Linked Lists: Insertion

▪The following Table shows the effect of these


statements.

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 29
Types of Linked Lists:
Singly Linked Lists: Insertion at the Middle

▪Note that the sequence of statements to insert the node, that is,
▪ newNode->link = p->link;
▪ p->link = newNode;
▪is very important because to insert newNode in the list we only use one pointer, p, to
adjust the links of the nodes of the linked list.
▪Suppose that we reverse the sequence of the statements and execute the statements in
the following order:
▪ p->link = newNode;
▪ newNode->link = p->link;

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 30
Types of Linked Lists:
Singly Linked Lists: Insertion at the Beginning
▪In this operation, a new node is created and set as the new head.
▪Create a new node.
▪Set its next pointer to the current head.
▪Update the head to point to the new node.
Node* insertAtBeginning(Node* head, int value) {
Node* newNode = createNode(value);
newNode->next = head;
return newNode; // New head
}
▪Example Usage: head = insertAtBeginning(head, 10);
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 31
Types of Linked Lists:
Singly Linked Lists: Insertion at the End
▪In this operation, inserts a node at the last position.
▪Traverse to the last node (where next is nullptr).
▪Create a new node and set its next pointer to nullptr.
▪Update the next pointer of the last node to point to the new node.
void insertAtEnd(int value) { Node* current = head;
Node* newNode = new Node(); while (current->next != nullptr) {
newNode->data = value; current = current->next;
newNode->next = nullptr; }
if (head == nullptr) { current->next = newNode;
head = newNode; }
} }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 32
Types of Linked Lists:
Singly Linked Lists: Deletion in the Middle

▪Traverse to the node before the node to be deleted.


▪Update the next pointer of the current node to skip the node to be deleted.
▪Free the memory of the deleted node.
▪Consider the linked list shown in the following figure: before Deletion

▪Suppose that the node with info 34 is to be deleted from the list.
▪The following statement removes the node from the list:
p->link = p->link->link;

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 33
Types of Linked Lists:
Singly Linked Lists: Deletion in the Middle
▪From the Figure above, it is clear that the node with info 34 is removed from
the list.
▪However, the memory is still occupied by this node and this memory is
inaccessible; that is, this node is dangling. To deallocate the memory, we
need a pointer to this node.
▪The following statements delete the node from the list and deallocate the
memory occupied by this node:
q = p->link;
p->link = q->link;
delete q;
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 34
Types of Linked Lists:
Singly Linked Lists: Deletion in the Middle

▪The following table shows the effect of these


statements.

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 35
Types of Linked Lists:
Singly Linked Lists: Deletion at the Beginning
▪Removes the first node and updates the head.
▪Update the head to point to the second node.
▪Free the memory of the deleted node.
Node* deleteAtBeginning(Node* head) {
if (head == nullptr) return nullptr;
Node* temp = head;
head = head->next;
delete temp;
return head;
}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 36
Types of Linked Lists:
Singly Linked Lists: Deletion at the Last Position
▪Removes the last node.
▪Traverse to the second-to-last node.
▪Update its next pointer to nullptr.
▪Free the memory of the deleted node.
Node* deleteAtEnd(Node* head) { Node* temp = head;

if (head == nullptr) return nullptr; while(temp->next->next!= nullptr)


{
if (head->next == nullptr) {
temp = temp->next; }
delete head;
delete temp->next;
return nullptr; } temp->next = nullptr;
return head; }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 37
Types of Linked Lists:
Singly Linked Lists: Deletion at the Last Position
Example
▪Consider the following linked list: head -> 10 -> 20 -> 30 -> nullptr
Step-by-Step Explanation
Step 1: Check if the List is Empty
▪If the list is empty (head == nullptr), there’s nothing to delete. Print an
error message and exit.
▪In our example, the list is not empty, so we proceed.
Step 2: Handle the Case Where the List Has Only One Node
▪If the list has only one node (head->next == nullptr), delete
the head node and set head to nullptr.
▪In our example, the list has multiple nodes, so we skip this step.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 38
Types of Linked Lists:
Singly Linked Lists: Deletion at the Last Position
Example
▪Consider the following linked list: head -> 10 -> 20 -> 30 -> nullptr
Step-by-Step Explanation
Step 3: Traverse to the Second-to-Last Node
▪Start from the head and traverse the list until the second-to-last node is reached.
▪Use a while loop to check if the next pointer of the current node points to the last
node (i.e., current->next->next == nullptr).
▪Initial State: head -> 10 -> 20 -> 30 -> nullptr
current starts at head (node 10)
▪After First Iteration: head -> 10 -> 20 -> 30 -> nullptr
current moves to node 20 (since current->next->next is 30->next, which
is nullptr)
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 39
Types of Linked Lists:
Singly Linked Lists: Deletion at the Last Position
Example
▪Consider the following linked list: head -> 10 -> 20 -> 30 -> nullptr
Step-by-Step Explanation
Step 4: Delete the Last Node
▪Once the second-to-last node (20) is reached:
▪Store the last node (30) in a temporary pointer (temp).
▪Update the next pointer of the second-to-last node (20)
to nullptr.
▪Delete the last node (30) using the delete keyword.
▪Final State: head -> 10 -> 20 -> nullptr
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 40
DOUBLY-LINKED LIST
(DLL)
Types of Linked Lists:
Doubly Linked List (DLL)
▪ A Doubly Linked List (DLL) is a type of linked list where each node contains three components:

1.Data – The value stored in the node.

2.Pointer to the next node – Links the current node to the next node.

3.Pointer to the previous node – Links the current node to the previous node.

▪ A doubly linked list is one where there are links from each node in both directions (previous
node and next).

▪ There are two NULL: at the first and last nodes in the list

▪ Advantage: given a node, it is easy to visit its predecessor. Convenient to traverse lists
backwards

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 42
Types of Linked Lists:
Doubly Linked List (DLL): Declaration

struct NodeType {
ItemType info;
NodeType * next;
NodeType * back;
};
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 43
Types of Linked Lists:
Doubly Linked List (DLL): Insertion

data data data

data

data data data

data

data data data

data

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 44
Types of Linked Lists:
Doubly Linked List (DLL): Deletion

data data data data

data data data data

data data data data

data data data data

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 45
Types of Linked Lists:
Doubly Linked List (DLL): Insertion: Example

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 46
Types of Linked Lists:
Doubly Linked List (DLL): Insertion: Example

1. newNode->back = location->back;
2. newNode->next = location
3. location->back->next=newNode;
4. location->back = newNode;
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 47
Types of Linked Lists:
Doubly Linked List (DLL): Deletion

head current

oldNode = current;
oldNode->prev->next = oldNode->next;
oldNode->next->prev = oldNode->prev;
delete oldNode;
current = head;
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 48
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/*

* Node Declaration

*/

struct node

int data;

node *next;

node *prev;

};
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 49
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Function Declarations or Prototypes */
void displayMenu();
void createList(Node** head, Node** tail);
void insertAtBeginning(Node** head, Node** tail);
void insertAtEnd(Node** head, Node** tail);
void insertAfter(Node** head, Node** tail);
void deleteFromBeginning(Node**head, Node** tail);
void deleteFromEnd(Node** head, Node** tail);
void deleteNode(Node** head, Node** tail);
void search(Node* head);
void displayForward(Node* head);
void displayBackward(Node* tail);
bool isEmpty(Node* head);
int countElements(Node* head);
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 50
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* The Main Function */ case 5: deleteFromBeginning(&head,
int main() { &tail); break;
case 6: deleteFromEnd(&head, &tail);
Node* head = nullptr;
break;
Node* tail = nullptr; case 7: deleteNode(&head, &tail);
int choice; break;
do { case 8: search(head); break;
displayMenu(); case 9: displayForward(head); break;
cout << "Enter your choice: "; case 10: displayBackward(tail); break;
cin >> choice; case 11: cout << "Number of elements: " <<
countElements(head); break;
switch(choice) { case 0: cout << "Exiting program...\n";
case 1: createList(&head, &tail); break; break;
case 2: insertAtBeginning(&head, &tail); default: cout << "Invalid choice! Try
break; again.\n"; }
case 3: insertAtEnd(&head, &tail); break; } while(choice != 0);
case 4: insertAfter(&head, &tail); break; return 0; }

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 51
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* The Display Function */
void displayMenu() {
cout << "\nDoubly Linked List Operations:\n";
cout << "1. Create/Reset List\n";
cout << "2. Insert at Beginning\n";
cout << "3. Insert at End\n";
cout << "4. Insert After a Node\n";
cout << "5. Delete from Beginning\n";
cout << "6. Delete from End\n";
cout << "7. Delete a Specific Node\n";
cout << "8. Search for a Node\n";
cout << "9. Display Forward\n";
cout << "10. Display Backward\n";
cout << "11. Count Elements\n";
cout << "0. Exit\n"; }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 52
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* The creating the list and check if the list empty */
void createList(Node** head, Node** tail) {
// Delete existing list if any
while(*head != nullptr) {
Node* temp = *head;
*head = (*head)->next;
delete temp; }
*tail = nullptr;
cout << "New empty list created.\n"; }
bool isEmpty(Node* head) {
if(head == nullptr) {
cout << "List is empty!\n";
return true; }
return false;
}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 53
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Insert at the beginning*/
void insertAtBeginning(Node** head, Node** tail) {
int val;
cout << "Enter value to insert at beginning: ";
cin >> val;
Node* newNode = new Node{val, nullptr, *head};
if(*head == nullptr) {
*tail = newNode;
} else {
(*head)->prev = newNode; }
*head = newNode;
cout << val << " inserted at beginning.\n"; }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 54
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Insert at the end*/
void insertAtEnd(Node** head, Node** tail) {
int val;
cout << "Enter value to insert at end: ";
cin >> val;
Node* newNode = new Node{val, *tail, nullptr};
if(*head == nullptr) {
*head = newNode;
} else {
(*tail)->next = newNode; }
*tail = newNode;
cout << val << " inserted at end.\n";}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 55
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Insert at the middle*/
void insertAfter(Node** head, Node** tail) {
if(isEmpty(*head)) return;
int target, val;
cout << "Enter the value after which to insert: ";
cin >> target;
cout << "Enter value to insert: ";
cin >> val;
Node* current = *head;
while(current != nullptr && current->data != target) {
current = current->next; }
if(current == nullptr) {
cout << target << " not found in list.\n";
return; }
Node* newNode = new Node{val, current, current->next};
if(current->next != nullptr) {
current->next->prev = newNode;
} else {
*tail = newNode; } // Update tail if inserting at end
current->next = newNode;
cout << val << " inserted after " << target << ".\n"; }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 56
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Delete from beginning*/
void deleteFromBeginning(Node** head, Node** tail) {
if(isEmpty(*head)) return;
Node* temp = *head;
*head = (*head)->next;
if(*head != nullptr) {
(*head)->prev = nullptr;
} else {
*tail = nullptr; } // List is now empty
cout << temp->data << " deleted from beginning.\n";
delete temp;
}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 57
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Delete from end*/
void deleteFromEnd(Node** head, Node** tail) {
if(isEmpty(*head)) return;
Node* temp = *tail;
*tail = (*tail)->prev;
if(*tail != nullptr) {
(*tail)->next = nullptr;
} else {
*head = nullptr;} // List is now empty
cout << temp->data << " deleted from end.\n";
delete temp; }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 58
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Delete from middle*/
void deleteNode(Node** head, Node** tail) {
if(isEmpty(*head)) return;
int val;
cout << "Enter value to delete: ";
cin >> val;
Node* current = *head;
while(current != nullptr && current->data != val) {
current = current->next; }
if(current == nullptr) {
cout << val << " not found in list.\n";
return; }
if(current == *head) {
deleteFromBeginning(head, tail);
} else if(current == *tail) {
deleteFromEnd(head, tail);
} else {
current->prev->next = current->next;
current->next->prev = current->prev;
cout << current->data << " deleted from list.\n";
delete current; } }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 59
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Search for an element*/
void search(Node* head) {
if(isEmpty(head)) return;
int val;
cout << "Enter value to search: ";
cin >> val;
Node* current = head;
int position = 1;
while(current != nullptr) {
if(current->data == val) {
cout << val << " found at position " << position << ".\n";
return; }
current = current->next;
position++; }
cout << val << " not found in list.\n"; }
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 60
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Display all elements from start to end */
void displayForward(Node* head) {
if(isEmpty(head)) return;

cout << "List (forward): ";


while(head != nullptr) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 61
Types of Linked Lists:
Doubly Linked List (DLL): Operations
/* Display all elements from end to start */
void displayBackward(Node* tail) {
if(tail == nullptr) {
cout << "List is empty!\n";
return; }
cout << "List (backward): ";
while(tail != nullptr) {
cout << tail->data << " ";
tail = tail->prev; }
cout << endl;
}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 62
Types of Linked Lists:
Doubly Linked List (DLL): Operations

/*
* Number of elements in Doubly Link List
*/
int countElements(Node* head) {
int count = 0;
Node* current = head;
while (current != nullptr) {
count++;
current = current->next;
}
return count;
}
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 63
CIRCULAR LINKED LIST
(CLL)
Types of Linked Lists:
Circular Linked List (CLL)
▪A Circular Linked List (CLL) is a variation of a linked list in which the last node points back to the first node,
forming a circle. There are two types of circular linked lists:
1.Singly Circular Linked List – Each node has a next pointer, and the last node points to the first
node.
▪ Traversal is only forward.
2.Doubly Circular Linked List – Each node has both next and prev pointers, forming a two-way
circular connection.
▪ The head->prev points to the tail, and tail->next points to head.
▪ Allows bidirectional traversal.
▪Real-World Examples:
1. Music Playlist (SCLL): Songs loop back to the first track when the last song ends.
2. Multiplayer Game Turns (DCLL): Players take turns in a loop, and the game can move forward or
backward.
3. CPU Scheduling (Round-Robin Algorithm) – Tasks are executed in a cyclic order.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 65
Types of Linked Lists:
Singly Circular Linked List (SCLL): Operations
1. Create the List
▪ Initialize head = nullptr.
2. Insert & Delete from Beginning
1. Insert:
▪ New node’s next points to head.
▪ Last node’s next updates to new node.
▪ Update head to new node.
2.Delete:
▪ Traverse to last node, update its next to head->next.
▪ Delete head and update head to head->next.
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 66
Types of Linked Lists:
Singly Circular Linked List (SCLL): Operations

3. Insert & Delete from Middle


1.Insert:
▪ Traverse to the desired position.
▪ Adjust next pointers of neighboring nodes.

2.Delete:
▪ Locate node, update previous node’s next to skip the node.

▪ Free the node memory.


4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 67
Types of Linked Lists:
Singly Circular Linked List (SCLL): Operations
4. Insert & Delete from End
1. Insert:

▪ Traverse to last node.

▪ New node’s next points to head.

▪ Last node’s next points to new node.

2. Delete:

▪ Traverse to second-last node.

▪ Update its next to head.

▪ Delete last node.

5. Search for an Element

▪ Traverse until the element is found (loop stops when back at head).

6. Check if List is Empty

▪ Return (head == nullptr).


4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 68
Types of Linked Lists:
Doubly Circular Linked List (DCLL): Operations
1. Create the List
▪ Initialize head = nullptr.
2. Insert & Delete from Beginning
1. Insert:
▪ New node's next points to current head
▪ New node's prev points to tail
▪ Update head->prev and tail->next to new node
▪ Set head to new node
2. Delete:
▪ If only one node, delete it and set head = nullptr
▪ Otherwise, adjust head->next->prev to tail and tail->next to head->next
▪ Delete old head and update head

4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 69
Types of Linked Lists:
Doubly Circular Linked List (DCLL): Operations

3. Insert & Delete from Middle


1. Insert:
▪ Traverse to desired position
▪ Adjust next and prev pointers of neighboring nodes
2.Delete:
▪ Locate node to delete

▪ Update prev->next and next->prev pointers

▪ Free the node memory


4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 70
Types of Linked Lists:
Doubly Circular Linked List (DCLL): Operations
4. Insert & Delete from End
1. Insert:

▪ New node's next points to head

▪ New node's prev points to current tail

▪ Update tail->next and head->prev to new node

2. Delete:

▪ Update tail->prev->next to head

▪ Update head->prev to new tail

▪ Delete old tail node

5. Search for an Element


▪ Traverse forward or backward until element is found
▪ Loop stops when we return to head
6. Check if List is Empty
▪ Return (head == nullptr).
4/14/2025 Data Structures and Algorithms Chapter Three: Linked Lists By: Kibru G. 71

You might also like