C++ Code Example 6: LinkedList Class Template Example

In this example, the “LinkedList” class template takes a type parameter “T” that represents the type of the elements that the linked list can hold. The class template provides methods for adding and removing elements from the front of the linked list, and for printing the contents of the linked list.

The main function demonstrates how the “LinkedList” class template can be used with different types of data. It creates two instances of the “LinkedList” class, one for integers and one for strings. It adds three elements to each linked list, prints the contents of the linked list, and removes the first element from the linked list.

Note that the type parameter “T” is again inferred from the data types of the variables used to create instances of the “LinkedList” class template. This allows the “LinkedList” class template to work with different types of data using the same code.

#include <iostream>

template <typename T>
class LinkedList {
private:
    struct Node {
        T data;
        Node* next;
        Node(T data) : data(data), next(nullptr) {}
    };
    Node* head;
public:
    LinkedList() : head(nullptr) {}
    ~LinkedList() {
        while (head) {
            Node* next = head->next;
            delete head;
            head = next;
        }
    }
    void push_front(T value) {
        Node* node = new Node(value);
        node->next = head;
        head = node;
    }
    void pop_front() {
        if (head) {
            Node* node = head;
            head = head->next;
            delete node;
        }
    }
    void print() const {
        Node* node = head;
        while (node) {
            std::cout << node->data << " ";
            node = node->next;
        }
        std::cout << std::endl;
    }
};

int main() {
    LinkedList<int> int_list;
    int_list.push_front(1);
    int_list.push_front(2);
    int_list.push_front(3);
    int_list.print();
    int_list.pop_front();
    int_list.print();

    LinkedList<std::string> string_list;
    string_list.push_front("Hello");
    string_list.push_front("World");
    string_list.push_front("!");
    string_list.print();
    string_list.pop_front();
    string_list.print();

    return 0;
}