OneCompiler

Linked list and display its elements in C++

301

#include <iostream>

// Define the structure of each node in the linked list
struct Node {
int data;
Node* next;

// Constructor to initialize node with given data and next pointer
Node(int value) : data(value), next(nullptr) {}

};

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

int main() {
// Creating linked list: 1 -> 2 -> 3 -> 4 -> 5
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);

// Displaying elements of the linked list
displayLinkedList(head);

// Freeing memory allocated for the linked list nodes
Node* current = head;
while (current != nullptr) {
    Node* temp = current;
    current = current->next;
    delete temp;
}

return 0;

}