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

Singly Linked List

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

Singly Linked List

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

Singly Linked List Tutorial

A singly linked list is a fundamental data structure in computer


science and programming, 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. This linear
structure supports efficient insertion and deletion operations,
making it widely used in various applications. In this tutorial, we'll
explore the node structure, understand the operations on singly
linked lists (traversal, searching, length determination, insertion,
and deletion), and provide detailed explanations and code examples
to implement these operations effectively.

Understanding Node Structure


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.

Singly Linked List


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.
In most programming languages, a node in a singly linked list is
typically defined using a class or a struct.

// Definition of a Node in a singly linked list


struct Node {

// Data part of the node


int data;

// Pointer to the next node in the list


Node* next;

// Constructor to initialize the node with data


Node(int data)
{
this->data = data;
this->next = nullptr;
}
};
In this example, the Node class contains an integer data field (data)
to store the information and a pointer to another Node (next) to
establish the link to the next node in the list.

Operations on Singly Linked List


 Traversal
 Searching
 Insertion:
o Insert at the beginning
o Insert at the end
o Insert at a specific position
 Deletion:
o Delete from the beginning
o Delete from the end
o Delete a specific node
Let's go through each of the operations mentioned above, one by
one.

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.
Below is the function for searching in singly linked list:

// Function to search for a value in the Linked List


bool searchLinkedList(struct Node* head, int target)
{
// Traverse the Linked List
while (head != nullptr) {

// Check if the current node's


// data matches the target value
if (head->data == target) {
return true; // Value found
}

// Move to the next node


head = head->next;
}

return false; // Value not found


}

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:
Insert a Node at the Front/Beginning of 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.
Below is the function for insertion at the beginning of singly linked
list:

// Function to insert a new node at the beginning of the linked list


struct Node* insertAtBeginning(struct Node* head, int value)
{
// Create a new node with the given value
struct Node* new_node = newNode(value);

// Set the next pointer of the new node to the current head
new_node->next = head;

// Move the head to point to the new node


head = new_node;
// Return the new head of the linked list
return head;
}

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-

Insertion at end of Linked List


Step-by-step approach:
 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.
Below is the function for insertion at the end of singly linked list:
C++CJavaPythonJavaScript
// Function to insert a node at the end of the linked list
struct Node* insertAtEnd(struct Node* head, int value)
{
// Create a new node with the given value
struct Node* new_node = newNode(value);

// If the list is empty, make the new node the head


if (head == NULL)
return new_node;

// Traverse the list until the last node is reached


struct Node* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}

// Link the new node to the current last node


curr->next = new_node;

return head;
}
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.
Below is the function for insertion at a specific position of the singly
linked list:

// Function to insert a node at a specified position


struct Node* insertPos(struct Node* head, int pos, int data) {
if (pos < 1) {
printf("Invalid position!\n");
return head;
}

// Special case for inserting at the head


if (pos == 1) {
struct Node* temp = getNode(data);
temp->next = head;
return temp;
}

// Traverse the list to find the node


// before the insertion point
struct Node* prev = head;
int count = 1;
while (count < pos - 1 && prev != NULL) {
prev = prev->next;
count++;
}

// If position is greater than the number of nodes


if (prev == NULL) {
printf("Invalid position!\n");
return head;
}

// Insert the new node at the specified position


struct Node* temp = getNode(data);
temp->next = prev->next;
prev->next = temp;

return head;
}
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.
Deletion at beginning in a Linked 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.
Below is the function for deletion at the beginning of singly linked
list:

// Function to remove the first node of the linked list


struct Node* removeFirstNode(struct Node* head)
{
if (head == NULL)
return NULL;

// Move the head pointer to the next node


struct Node* temp = head;
head = head->next;

// Free the memory of the old head


free(temp);

return head;
}
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.

Deletion at the end of linked list


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.
Below is the function for deletion at the end of singly linked list:
// Function to remove the last node of the linked list
struct Node* removeLastNode(struct Node* head)
{
if (head == NULL)
return NULL;

if (head->next == NULL) {
free(head);
return NULL;
}

// Find the second last node


struct Node* second_last = head;
while (second_last->next->next != NULL)
second_last = second_last->next;

// Delete last node


free(second_last->next);

// Change next of second last


second_last->next = NULL;

return head;
}

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.
Delete a Linked List node at a given position

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.
 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.
Below is the function for deletion at a specific position of singly
linked list:

// Function to delete a node at a specific position


struct Node* deleteAtPosition(struct Node* head, int position)
{
// If the list is empty or the position is invalid
if (head == NULL || position < 1) {
return head;
}

// If the head needs to be deleted


if (position == 1) {
struct Node* temp = head;
head = head->next;
free(temp);
return head;
}

// Traverse to the node before the position to be deleted


struct Node* curr = head;
for (int i = 1; i < position - 1 && curr != NULL; i++) {
curr = curr->next;
}

// If the position is out of range


if (curr == NULL || curr->next == NULL) {
return head;
}

// Store the node to be deleted


struct Node* temp = curr->next;

// Update the links to bypass the node to be deleted


curr->next = curr->next->next;

// Delete the node


free(temp);

return head;
}
What is a 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.
Doubly Linked List
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)

struct Node {

// To store the Value or data.


int data;

// Pointer to point the Previous Element


Node* prev;

// Pointer to point the Next Element


Node* next;
};

// Function to create a new node


struct Node *createNode(int new_data) {
struct Node *new_node = (struct Node *)
malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
new_node->prev = NULL;
return new_node;
}
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
 Searching in Doubly Linked List
 Insertion in Doubly Linked List :
o Insertion at the beginning of Doubly Linked List
o Insertion at the end of the Doubly Linked List
o Insertion at a specific position in Doubly Linked List
 Deletion in Doubly Linked List :
o Deletion of a node at the beginning of Doubly Linked List
o Deletion of a node at the end of Doubly Linked List
o Deletion of a node at a specific position in Doubly Linked List

Insert a Node at Front/Beginning of Doubly


Linked List


Given a Doubly Linked List, the task is to insert a new node at


the beginning/start/front of the linked list.
Examples:
Input: Linked List = 2 <-> 3 <-> 4 -> NULL , New Node = 1
Output: 1 <-> 2 <-> 3 <-> 4 -> NULL
Explanation: Node 1 is inserted at the beginning and is the new head of the doubly linked
list.
Input: Linked List = NULL, New Node = 10
Output: 10 -> NULL
Explanation: Node 1 is the only node in the doubly linked list.

Approach:
To insert a new node at the beginning/front of doubly linked list, we create a new node
with its previous pointer as NULL and next pointer to the current head of the doubly linked
list. Then, we check if the linked list is not empty then we update the previous pointer of
the current head to the new node. Finally, we return the new node as the head of the
linked list.

Insert Node 1 at Front/Beginning of Doubly Linked List

Steps to insert a node at the beginning of doubly linked list:


 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 the 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.

// C Program to insert a node at the beginning of doubly


// linked list

#include <stdio.h>
struct Node {
int data;
struct Node *next;
struct Node *prev
};

// Function to create a new node


struct Node *createNode(int new_data) {
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
new_node->prev = NULL;
return new_node;
}

// Function to insert a new node at the front of doubly linked list


struct Node *insertAtFront(struct Node *head, int new_data) {

// Create a new node


struct Node *new_node = createNode(new_data);

// Make next of new node as head


new_node->next = head;

// Change prev of head node to new node


if (head != NULL) {
head->prev = new_node;
}

// Return the new node as the head of the doubly linked list
return new_node;
}

// Function to print the doubly linked list


void printList(struct Node *head) {
struct Node *curr = head;
while (curr != NULL) {
printf(" %d", curr->data);
curr = curr->next;
}
printf("\n");
}

int main() {

// Create a hardcoded doubly linked list:


// 2 <-> 3 <-> 4 -> NULL
struct Node *head = createNode(2);
head->next = createNode(3);
head->next->prev = head;
head->next->next = createNode(4);
head->next->next->prev = head->next;

// Print the original list


printf("Original Linked List:");
printList(head);

// Insert a new node at the front of the list


printf("After inserting Node at the front:");
int data = 1;
head = insertAtFront(head, data);

// Print the updated list


printList(head);

return 0;
}

Output
Original Linked List: 2 3 4
After inserting Node at the front: 1 2 3 4
Time Complexity: O(1)
Auxiliary Space: O(1)

Insert a Node at the end of Doubly Linked List


Last Updated : 07 Aug, 2024



Given a Doubly Linked List, the task is to insert a new node at the end of the
linked list.
Examples:
Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4
Output: Linked List = 1 <-> 2 <-> 3 <-> 4
Input: Linked List = NULL, NewNode = 1
Output: Linked List = 1

Approach:
Inserting at the end involves traversing the entire list until we reach the last
node. We then set the last node’s next reference to point to the new node
and new node's previous reference to point to the last node. Thus, making
the new node the last element in the list.

Insert node 4 at the end of Doubly Linked List


Steps to insert a new node at the end:
 If the linked list is empty, we set the new node as the head of linked list and
return it as the new head of the linked list.
 Otherwise, traverse the entire list until we reach the last node, say curr.
 Then, set the last node’s next to new node and new node’s prev to last node,
making the new node the last element in the list.

// C Program to insert a node at the end of doubly linked list

#include <stdio.h>

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

// Function to create a new node with the given data


struct Node *createNode(int new_data) {
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}

// Function to insert a new node at the end of the doubly linked list
struct Node* insertEnd(struct Node *head, int new_data) {
struct Node *new_node = createNode(new_data);

// If the linked list is empty, set the new node as the head
if (head == NULL) {
head = new_node;
} else {
struct Node *curr = head;
while (curr->next != NULL) {
curr = curr->next;
}

// Set the next of last node to new node


curr->next = new_node;
// Set prev of new node to last node
new_node->prev = curr;
}

return head;
}

void printList(struct Node *head) {


struct Node *curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {

// Create a hardcoded doubly linked list:


// 1 <-> 2 <-> 3
struct Node *head = createNode(1);
head->next = createNode(2);
head->next->prev = head;
head->next->next = createNode(3);
head->next->next->prev = head->next;

// Print the original list


printf("Original Linked List: ");
printList(head);

// Insert a new node with data 4 at the end


printf("Inserting Node with data 4 at the end: ");
head = insertEnd(head, 4);

// Print the updated list


printList(head);

return 0;
}

Output
Original Linked List: 1 2 3
Inserting Node with data 4 at the end: 1 2 3 4
Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(1)

Deletion at end (Removal of last node) in a Doubly


Linked List


Given a doubly linked list, the task is to delete the last node of the given linked
list.
Examples:
Input: 1 <-> 2 <-> 3 <-> NULL
Output: 1 <-> 2 <-> NULL
Explanation: The last node of the linked list is 3, so 3 is deleted.
Input: 15 -> NULL
Output: NULL
Explanation: The last node of the linked list is 15, so 15 is deleted.

Approach:
To perform the deletion operation at the end of doubly linked list, we need to
traverse the list to find the second last node, then set its next pointer to null.

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.

// C Program to delete a node from the end of Doubly Linked List

#include <stdio.h>

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

// Function to delete the last node of the doubly linked list


struct Node* delLast(struct Node *head) {

// Corner cases
if (head == NULL)
return NULL;
if (head->next == NULL) {
free(head);
return NULL;
}

// Traverse to the last node


struct Node *curr = head;
while (curr->next != NULL)
curr = curr->next;

// Update the previous node's next pointer


curr->prev->next = NULL;

// Delete the last node


free(curr);

// Return the updated head


return head;
}

// Function to print the list


void printList(struct Node *head) {
struct Node *curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}

// Function to create a new node


struct Node* createNode(int data) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

int main() {

// Create a hardcoded doubly linked list:


// 1 <-> 2 <-> 3
struct Node *head = createNode(1);
head->next = createNode(2);
head->next->prev = head;
head->next->next = createNode(3);
head->next->next->prev = head->next;

printf("Original Linked List: ");


printList(head);

printf("After Deletion at the end: ");


head = delLast(head);

printList(head);

return 0;
}

Output
Original Linked List: 1 2 3
After Deletion at the end: 1 2
Time Complexity: O(N), where N is the number of nodes in the linked list
Auxiliary Space: O(1)

You might also like