Linked List Example C/C++

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.3 kB
2
Indexable
#include <iostream>

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

class LinkedList {
private:
    Node* head;

public:
    Node* getHead() {
        return head;
    }

    LinkedList() : head(nullptr) {}

    ~LinkedList() {
        while (head != nullptr) {
            Node* temp = head;
            head = head->next;
            delete temp;
        }
    }

    void append(int data) {
        Node* new_node = new Node{data, nullptr};
        if (head == nullptr) {
            head = new_node;
        } else {
            Node* current = head;
            while (current->next != nullptr) {
                current = current->next;
            }
            current->next = new_node;
        }
    }

    void print() {
        Node* current = head;
        while (current != nullptr) {
            std::cout << current->data << std::endl;
            current = current->next;
        }
    }
};

int main() {
    LinkedList list;
    list.append(1);
    list.append(2);
    list.append(3);
    Node* current = list.getHead();
    while (current != nullptr) {
        std::cout << current->data << std::endl;
        current = current->next;
    }
    std::cout << current->data << '\n';
    return 0;
}