A linked list in C++ is a linear data structure storing elements in separate objects called nodes. Each node contains two parts: data and a pointer(reference) to the next node in the sequence. This structure allows for the Linked List’s dynamic memory allocation, insertion, and deletion operations.
Linked List Program in C++
Here’s an example of a linked list program in C++ along with an explanation:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
next = nullptr;
}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = nullptr;
}
// Method to insert a new node at the end of the linked list
void append(int data) {
Node* newNode = new Node(data);
if (head == nullptr) {
head = newNode;
return;
}
Node* last = head;
while (last->next != nullptr) {
last = last->next;
}
last->next = newNode;
}
// Method to display the linked list elements
void display() {
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.append(1);
list.append(2);
list.append(3);
list.append(4);
cout << "Linked List elements:" << endl;
list.display();
return 0;
}
Explanation: LinkedList Program
- The Node class represents each node in the linked list. It has a data field and a pointer to the next node.
- The LinkedList class manages the linked list operations. It has a head pointer to the first node in the list.
- The append method adds a new node with the given data at the end of the linked list.
- The display method prints all the elements of the linked list.
- In the main function, we create a linked list object, add elements to it using the append method, and then display the elements using the display method.