allizwell.jobsdoor360.in

Singly Linked List

Data Structures and Algorithms / Linked Lists / Singly Linked List

Singly Linked List in C++

A Singly Linked List is the simplest type of linked list. Each node contains data and a pointer to the next node. The last node points to nullptr, indicating the end of the list. In this topic, we will understand its structure, memory representation, traversal, searching, and implementation using C++.

1. What Is a Singly Linked List?

A Singly Linked List is a linear data structure made up of nodes connected through pointers. Each node stores a value and the address of the next node.

The list starts with a pointer called head. Head stores the address of the first node. The final node points to nullptr.

Example

Head
 |
 v
+------+------+
|  10  | next |----->
+------+------+
                  |
                  v
             +------+------+
             |  20  | next |----->
             +------+------+
                              |
                              v
                         +------+------+
                         |  30  | NULL |
                         +------+------+

This linked list contains three nodes with values 10, 20, and 30. Each node points to the next node.

2. Structure of a Singly Linked List Node

Every node in a singly linked list contains two parts:

  • Data: Stores the value of the node.
  • Next pointer: Stores the address of the next node.

C++ Node Structure

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

Explanation:

  • int data stores an integer value.
  • Node* next stores the address of another Node.
  • The next pointer is used to connect one node to another.

3. Important Components

1. Head Pointer

The head pointer stores the address of the first node. It is the entry point of the linked list.

Node* head = nullptr;

If head is nullptr, the linked list is empty.

2. Data Field

The data field stores the actual information inside a node. For example:

newNode->data = 100;

3. Next Pointer

The next pointer connects the current node to the following node.

newNode->next = anotherNode;

4. Last Node

The last node does not point to another node. Its next pointer contains nullptr.

lastNode->next = nullptr;

4. Creating a Singly Linked List

We can create nodes dynamically using the new operator in C++. Let's create a linked list with three nodes.

C++ Program

#include <iostream>
using namespace std;

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

int main() {

    Node* first = new Node();
    Node* second = new Node();
    Node* third = new Node();

    first->data = 10;
    second->data = 20;
    third->data = 30;

    first->next = second;
    second->next = third;
    third->next = nullptr;

    Node* head = first;

    cout << "First node: " << head->data << endl;

    delete first;
    delete second;
    delete third;

    return 0;
}

Output

First node: 10

Three nodes are created and connected. The head pointer stores the address of the first node.

5. How Nodes Are Connected

Suppose we have three nodes:

Node A: data = 10
Node B: data = 20
Node C: data = 30

We connect them using their next pointers:

A->next = B;
B->next = C;
C->next = nullptr;

The final structure becomes:

Head
 |
 v
[10 | next] -> [20 | next] -> [30 | NULL]
Remember: A singly linked list allows movement only in the forward direction because every node stores only the address of its next node.

6. Traversing a Singly Linked List

Traversal means visiting every node of the linked list one by one. We start from head and follow the next pointer until nullptr.

Algorithm

  1. Create a temporary pointer and assign head to it.
  2. Check whether the temporary pointer is not nullptr.
  3. Print or process the current node's data.
  4. Move the temporary pointer to the next node.
  5. Repeat until the pointer becomes nullptr.

C++ Program

#include <iostream>
using namespace std;

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

void display(Node* head) {

    Node* temp = head;

    while (temp != nullptr) {

        cout << temp->data << " ";

        temp = temp->next;
    }

    cout << endl;
}

int main() {

    Node* first = new Node{10, nullptr};
    Node* second = new Node{20, nullptr};
    Node* third = new Node{30, nullptr};

    first->next = second;
    second->next = third;

    Node* head = first;

    display(head);

    delete first;
    delete second;
    delete third;

    return 0;
}

Output

10 20 30

7. Understanding Traversal Step by Step

Consider this linked list:

Head
 |
 v
10 -> 20 -> 30 -> NULL
Step Current Node Printed Value Next Position
1 First node 10 Second node
2 Second node 20 Third node
3 Third node 30 nullptr
4 nullptr Nothing Traversal stops

When temp becomes nullptr, the loop terminates because there are no more nodes to visit.

8. Searching in a Singly Linked List

Searching means finding whether a particular value exists in the linked list.

Since a singly linked list does not support direct index-based access, we start from the head and compare each node's data with the target value.

Algorithm

  1. Start from the head node.
  2. Compare the current node's data with the target value.
  3. If both values match, return the position or indicate success.
  4. Otherwise, move to the next node.
  5. If nullptr is reached, the value is not present.

C++ Program

#include <iostream>
using namespace std;

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

bool search(Node* head, int target) {

    Node* temp = head;

    while (temp != nullptr) {

        if (temp->data == target) {
            return true;
        }

        temp = temp->next;
    }

    return false;
}

int main() {

    Node* first = new Node{10, nullptr};
    Node* second = new Node{20, nullptr};
    Node* third = new Node{30, nullptr};

    first->next = second;
    second->next = third;

    Node* head = first;

    int target = 20;

    if (search(head, target)) {
        cout << "Element found";
    } else {
        cout << "Element not found";
    }

    delete first;
    delete second;
    delete third;

    return 0;
}

Output

Element found

9. Counting Nodes in a Singly Linked List

We can count the total number of nodes by traversing the list and increasing a counter for every node.

C++ Program

#include <iostream>
using namespace std;

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

int countNodes(Node* head) {

    int count = 0;

    Node* temp = head;

    while (temp != nullptr) {

        count++;

        temp = temp->next;
    }

    return count;
}

int main() {

    Node* first = new Node{10, nullptr};
    Node* second = new Node{20, nullptr};
    Node* third = new Node{30, nullptr};

    first->next = second;
    second->next = third;

    Node* head = first;

    cout << "Total nodes: " << countNodes(head);

    delete first;
    delete second;
    delete third;

    return 0;
}

Output

Total nodes: 3

10. Complete Singly Linked List Implementation Using a Class

We can organize linked list operations inside a C++ class. The following implementation creates a singly linked list, adds elements at the end, displays the list, searches for a value, and counts the nodes.

#include <iostream>
using namespace std;

class SinglyLinkedList {

private:

    struct Node {
        int data;
        Node* next;

        Node(int value) {
            data = value;
            next = nullptr;
        }
    };

    Node* head;

public:

    SinglyLinkedList() {
        head = nullptr;
    }

    // Add a node at the end
    void append(int value) {

        Node* newNode = new Node(value);

        if (head == nullptr) {
            head = newNode;
            return;
        }

        Node* temp = head;

        while (temp->next != nullptr) {
            temp = temp->next;
        }

        temp->next = newNode;
    }

    // Display the linked list
    void display() {

        Node* temp = head;

        while (temp != nullptr) {

            cout << temp->data << " -> ";

            temp = temp->next;
        }

        cout << "NULL" << endl;
    }

    // Search for a value
    bool search(int target) {

        Node* temp = head;

        while (temp != nullptr) {

            if (temp->data == target) {
                return true;
            }

            temp = temp->next;
        }

        return false;
    }

    // Count total nodes
    int countNodes() {

        int count = 0;

        Node* temp = head;

        while (temp != nullptr) {

            count++;

            temp = temp->next;
        }

        return count;
    }

    // Release all dynamically allocated nodes
    ~SinglyLinkedList() {

        Node* temp = head;

        while (temp != nullptr) {

            Node* nextNode = temp->next;

            delete temp;

            temp = nextNode;
        }
    }
};

int main() {

    SinglyLinkedList list;

    list.append(10);
    list.append(20);
    list.append(30);

    cout << "Linked List: ";
    list.display();

    cout << "Total Nodes: "
         << list.countNodes() << endl;

    if (list.search(20)) {
        cout << "20 is found" << endl;
    } else {
        cout << "20 is not found" << endl;
    }

    return 0;
}

Output

Linked List: 10 -> 20 -> 30 -> NULL

Total Nodes: 3

20 is found

Understanding the Class

  • Node: Defines the data and next pointer of each node.
  • head: Stores the first node's address.
  • append(): Adds a new node at the end.
  • display(): Prints all nodes.
  • search(): Checks whether a value exists.
  • countNodes(): Returns the total number of nodes.
  • Destructor: Releases all dynamically allocated nodes when the list object is destroyed.
Note: In this class implementation, append() takes O(n) time because it traverses the list to find the last node. A tail pointer can make appending O(1), but it must be maintained correctly when the list changes.

11. Advantages of a Singly Linked List

  • Dynamic size: nodes can be added or removed as needed.
  • Does not require contiguous memory locations.
  • Insertion at the beginning takes O(1) time.
  • Deletion at the beginning takes O(1) time.
  • Requires only one pointer field per node.
  • Useful for implementing stacks and other dynamic data structures.

12. Disadvantages of a Singly Linked List

  • Only forward traversal is possible.
  • Random access is not supported.
  • Searching takes O(n) time in the worst case.
  • Every node requires extra memory for its next pointer.
  • Finding the previous node is difficult because there is no previous pointer.
  • Pointer management requires careful programming.

13. Time and Space Complexity

Operation Time Complexity Explanation
Access by position O(n) Traverse from the head to the required position.
Traversal O(n) Visit every node once.
Search O(n) Check nodes one by one.
Insert at beginning O(1) Update the head pointer.
Delete at beginning O(1) Move head to the next node.
Insert at end O(n) Without a tail pointer, traverse to the last node.
Delete at end O(n) Find the second-last node.
Count nodes O(n) Traverse the entire list.

Space Complexity

For n nodes, the total storage required is O(n). Each node stores data and a pointer to the next node.

14. Singly Linked List vs Array

Feature Array Singly Linked List
Memory layout Contiguous Non-contiguous nodes
Access by index O(1) O(n)
Forward traversal Supported Supported
Backward traversal Possible using indices Not directly supported
Insert at beginning O(n) in general O(1)
Pointer memory No next pointer per element One next pointer per node
Dynamic growth Depends on array type Nodes can be added dynamically

15. Common Mistakes

1. Losing the Head Pointer

Do not move head directly during traversal. Use a temporary pointer so that the original starting address remains available.

2. Forgetting to Initialize Next

Always initialize the next pointer of a newly created final node to nullptr.

3. Accessing a Null Pointer

Check that a pointer is not nullptr before accessing its data or next field.

4. Incorrect Pointer Connections

Incorrect pointer updates can disconnect nodes and make part of the list inaccessible.

5. Forgetting to Free Memory

Dynamically allocated nodes should be released when they are no longer required.

16. Applications of Singly Linked Lists

  • Implementing stacks.
  • Implementing simple queues.
  • Representing sequences of connected data.
  • Maintaining dynamically changing collections.
  • Representing adjacency lists in graph implementations.
  • Building other linked data structures.

17. Interview Questions

Q1. What is a Singly Linked List?

It is a linear data structure in which every node contains data and a pointer to the next node.

Q2. What are the components of a node?

A singly linked list node contains a data field and a next pointer.

Q3. What is the role of head?

Head stores the address of the first node in the linked list.

Q4. Why does the last node point to nullptr?

It indicates that there is no next node and marks the end of the linked list.

Q5. Can we traverse a singly linked list backward?

Not directly. Each node stores only the address of the next node.

Q6. What is the time complexity of searching?

O(n) in the worst case because every node may need to be checked.

Q7. What is the time complexity of inserting at the beginning?

O(1), because only the new node's next pointer and head pointer need to be updated.

Q8. What happens when head is nullptr?

The linked list is empty and contains no nodes.

Q9. What is the difference between a singly and doubly linked list?

A singly linked list has one next pointer per node. A doubly linked list has both previous and next pointers.

Q10. How much extra pointer memory does each node require?

Each singly linked list node requires space for one next pointer, in addition to its data.

18. Practice Problems

  1. Create a singly linked list containing five nodes.
  2. Print all elements of a singly linked list.
  3. Count the total number of nodes.
  4. Search for a given value in the list.
  5. Find the maximum value in the linked list.
  6. Find the minimum value in the linked list.
  7. Calculate the sum of all node values.
  8. Print the last node of the linked list.
  9. Find the position of a given element.
  10. Implement a singly linked list using a C++ class.

19. Summary

  • A Singly Linked List is made up of connected nodes.
  • Each node contains data and a next pointer.
  • Head points to the first node.
  • The last node points to nullptr.
  • Traversal is possible only in the forward direction.
  • Searching and traversal take O(n) time.
  • Insertion at the beginning takes O(1) time.
  • Dynamic memory allocation is commonly used to create nodes.
Key Takeaway: A Singly Linked List connects nodes using one next pointer per node. Understanding node creation, pointer connections, and forward traversal is essential before learning insertion, deletion, reversal, and other linked list operations.
Scroll to Top