Mark As Completed Discussion

To add a new node to the linked list, follow these steps:

  1. Create a new node with the desired data.

  2. If the list is empty, make the new node the head of the list.

  3. Otherwise, traverse the list to find the last node.

  4. 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}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment