Implementation of a Singly Linked List

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int value;
    Node* next;
};

bool initialize(Node*& list) {
    list = new Node;
    if (!list) return false;
    list->next = nullptr;
    return true;
}

bool addAtHead(Node*& list, Node* element) {
    if (!list || !element) return false;
    element->next = list->next;
    list->next = element;
    return true;
}

bool addAtTail(Node*& list, Node* element) {
    if (!list || !element) return false;
    Node* current = list;
    while (current->next) {
        current = current->next;
    }
    element->next = nullptr;
    current->next = element;
    return true;
}

void display(Node*& list) {
    Node* current = list->next;
    while (current) {
        cout << current->value << " ";
        current = current->next;
    }
    cout << endl;
}

int main() {
    Node* head = nullptr;
    Node* node = nullptr;
    initialize(head);

    int data[9] = {5, 3, 2, 4, 8, 9, 7, 1, 10};
    for (auto i = 0; i < 9; i++) {
        node = new Node;
        node->value = data[i];
        addAtTail(head, node);
    }
    display(head);
    return 0;
}
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int value;
    Node* next;
};

class LinkedList {
public:
    LinkedList();
    void insert(Node* &current, int value);
    Node* head;
};

LinkedList::LinkedList() {
    head = new Node;
    head->next = nullptr;
}

void LinkedList::insert(Node*& current, int value) {
    if (current->next == nullptr) {
        Node* newNode = new Node;
        current->next = newNode;
        newNode->value = value;
        newNode->next = nullptr;
    } else {
        insert(current->next, value);
    }
}

void traverse(Node* current) {
    if (current->next != nullptr) {
        cout << current->next->value << " ";
        traverse(current->next);
    }
}

int main() {
    LinkedList* list = new LinkedList;
    int values[9] = {5, 3, 2, 4, 8, 9, 7, 1, 10};
    for (auto i = 0; i < 9; i++) {
        list->insert(list->head, values[i]);
    }
    traverse(list->head);
    return 0;
}

Tags: Linked List data structure C++

Posted on Sun, 31 May 2026 22:21:19 +0000 by rashpal