AlgoDocs

Singly Linked List

A unidirectional linear data structure

Introduction

A Singly linked list is a linear data structure, it consists of nodes where each node contains a data field and a pointer to the next node in the sequence. The last node points to null, marking the end of the list. It is memory-efficient and supports efficient insertion and deletion operations, especially at the beginning or middle, as no shifting of elements is required.

Visualization of Singly Linked List

Visualization of Singly Linked List

Operation on Singly Linked List

Insertion

  1. Insertion At Beginning

  2. Insertion At Position

  3. Insertion At Tail

Deletion

  1. Deletion At Beginning

  2. Deletion At Position

  3. Deletion At Tail

Traversal

  1. Initialize a pointer (current) to the head of the list.

  2. While (current!=null)

    • Process the data of the current node.

    • Move the pointer to the next node (current = current->next).

  3. The traversal stops when all nodes are processed.

// traversalonll.cpp
void traverseLinkedList(Node* head)
{
Node* current = head;
while (current != NULL) {
    cout << current->data << " ";
    current = current->next;
}
}
#traversalonll.py
def traverse_linked_list(head):
 current = head
 while current is not None:
     print(current.data),
     current = current.next
//traversalonll.js
function traverseLinkedList(head) {
 let current = head;
 while (current !== null) {
     console.log(current.data);
     current = current.next;
 }
}

Searching

  1. Start from the head of the linked list.
  2. Check if the current node's data matches the target value:
    • If a match is found, return true.
  3. Move to the next node.
  4. Repeat steps 2 and 3 until:
    • The target value is found (return true).
    • The end of the list is reached (return false).
//searchingonll.cpp
bool searchLinkedList(struct Node* head, int target)
{
while (head != NULL) {
    if (head->data == target) {
        return true;
    }
    head = head->next;
}
return false;
}
#searchingonll.py
def search_linked_list(head, target):
 while head is not None:
     if head.data == target:
         return True  
     head = head.next
 return False 

How is this guide?