To add a new node to the linked list, follow these steps:
Create a new node with the desired data.
If the list is empty, make the new node the head of the list.
Otherwise, traverse the list to find the last node.
Insert the new node at the end of the list by setting the
next
pointer of the last node to point to the new node.
Here's an example of adding a new node to a singly linked list in C++:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4class Node {
5public:
6 int data;
7 Node* next;
8
9 Node(int data) {
10 this->data = data;
11 next = nullptr;
12 }
13};
14
15int main() {
16 // Create the head of the list
17 Node* head = new Node(1);
18
19 // Add a new node
20 Node* newNode = new Node(2);
21
22 // Traverse the list to find the last node
23 Node* current = head;
24 while (current->next != nullptr) {
25 current = current->next;
26 }
27
28 // Insert the new node at the end of the list
29 current->next = newNode;
30
31 // Optional: Display the updated list
32 current = head;
33 while (current != nullptr) {
34 cout << current->data << " ";
35 current = current->next;
36 }
37
38 return 0;
39}
xxxxxxxxxx
30
}
using namespace std;
int main() {
// Create a new node
Node* newNode = new Node(data);
// If the list is empty, make the new node the head
if (head == nullptr) {
head = newNode;
}
// Otherwise, traverse the list to find the last node
else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
// Insert the new node at the end of the list
current->next = newNode;
}
// Optional: Display the updated list
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
return 0;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment