How to implement a singly linked list with insert, delete, and search operations in C++

1 Answer

0 votes
#include <iostream>

// A node in a singly linked list
struct Node {
    int value;      // data stored in the node
    Node* next;     // pointer to the next node

    Node(int v) : value(v), next(nullptr) {}
};

// Singly linked list class
class LinkedList {
private:
    Node* head;     // pointer to the first node

public:
    LinkedList() : head(nullptr) {}

    // Insert a new value at the end of the list
    void insert(int value) {
        Node* newNode = new Node(value);

        // If list is empty
        if (!head) {
            head = newNode;
            return;
        }

        // Otherwise, find the last node
        Node* temp = head;
        while (temp->next) {
            temp = temp->next;
        }

        temp->next = newNode;
    }

    // Search for a value in the list
    Node* search(int value) {
        Node* temp = head;
        while (temp) {
            if (temp->value == value)
                return temp;
            temp = temp->next;
        }
        return nullptr; // not found
    }

    // Delete the first node with the given value
    void remove(int value) {
        if (!head) return;

        // If the head is the node to delete
        if (head->value == value) {
            Node* toDelete = head;
            head = head->next;
            delete toDelete;
            return;
        }

        // Search for the node before the one to delete
        Node* temp = head;
        while (temp->next && temp->next->value != value) {
            temp = temp->next;
        }

        // If found
        if (temp->next) {
            Node* toDelete = temp->next;
            temp->next = temp->next->next;
            delete toDelete;
        }
    }

    // Print the list
    void print() {
        Node* temp = head;
        while (temp) {
            std::cout << temp->value;
            if (temp->next) std::cout << " -> ";
            temp = temp->next;
        }
        std::cout << std::endl;
    }
};

int main() {
    LinkedList list;

    // Insert values
    list.insert(10);
    list.insert(20);
    list.insert(30);
    list.insert(40);
    list.insert(50);

    std::cout << "List after inserts: ";
    list.print();

    // Search
    Node* found = list.search(30);
    if (found)
        std::cout << "Found: " << found->value << std::endl;
    else
        std::cout << "Value not found" << std::endl;

    // Delete
    list.remove(20);
    std::cout << "List after deleting 20: ";
    list.print();
}


/*
run:

List after inserts: 10 -> 20 -> 30 -> 40 -> 50
Found: 30
List after deleting 20: 10 -> 30 -> 40 -> 50

*/

 



answered Jun 30 by avibootz
...