You are on page 1of 3

#include <iostream>

// Define the Node class

class Node {

public:

int data;

Node* next;

// Constructor to initialize a node

Node(int val) : data(val), next(nullptr) {}

};

// Define the LinkedList class

class LinkedList {

private:

Node* head;

public:

// Constructor to initialize the linked list

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 == nullptr) {

head = newNode;

} else {

Node* temp = head;

while (temp->next != nullptr) {

temp = temp->next;

}
temp->next = newNode;

// Function to print all elements in the list

void display() {

Node* temp = head;

while (temp != nullptr) {

std::cout << temp->data << " ";

temp = temp->next;

std::cout << std::endl;

// Destructor to free the allocated memory

~LinkedList() {

while (head != nullptr) {

Node* temp = head;

head = head->next;

delete temp;

};

// Main function

int main() {

LinkedList list;

list.insert(1);

list.insert(2);

list.insert(3);

list.insert(4);
std::cout << "Elements of the list are: ";

list.display();

return 0;

You might also like