Cover Image for Create Linked List In C++
98 views

Create Linked List In C++

The C++ can create a singly linked list, a data structure that consists of nodes, each containing data and a pointer/reference to the next node in the list. Here’s an example of how to create a simple singly linked list in C++:

C++
#include <iostream>

// Define the structure for a singly linked list node
struct Node {
    int data;
    Node* next;

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

// Define the Linked List class
class LinkedList {
private:
    Node* head; // Pointer to the first node in the list

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

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

        if (!head) {
            head = newNode;
        } else {
            Node* current = head;
            while (current->next) {
                current = current->next;
            }
            current->next = newNode;
        }
    }

    // Function to display the elements of the list
    void display() {
        Node* current = head;
        while (current) {
            std::cout << current->data << " -> ";
            current = current->next;
        }
        std::cout << "nullptr" << std::endl;
    }

    // Destructor to free memory
    ~LinkedList() {
        Node* current = head;
        while (current) {
            Node* next = current->next;
            delete current;
            current = next;
        }
    }
};

int main() {
    LinkedList myList;

    myList.insert(1);
    myList.insert(2);
    myList.insert(3);

    std::cout << "Linked List: ";
    myList.display();

    return 0;
}

In this example:

  • We define a Node structure to represent the individual elements of the linked list. Each node has an integer data field and a pointer next that points to the next node in the list.
  • We define a LinkedList class that manages the linked list. It has a private head pointer that points to the first node in the list.
  • The insert function is used to insert a new node at the end of the list. If the list is empty, it sets the head to the new node; otherwise, it traverses the list to find the last node and adds the new node after it.
  • The display function is used to print the elements of the linked list.
  • In the main function, we create an instance of the LinkedList class, insert three values into the list, and then display the contents of the linked list.
  • Finally, we have a destructor for the LinkedList class that deallocates memory for all nodes when the list goes out of scope.

This is a basic example of how to create a singly linked list in C++. You can extend and modify it to suit your specific requirements.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS