Mark As Completed Discussion

To delete a node from a linked list, you need to find the node with the value you want to delete and update the links to remove it from the list. The code snippet below demonstrates how to delete a node from a linked list in C++:

TEXT/X-C++SRC
1// Node class
2class Node {
3public:
4    int data;
5    Node* next;
6
7    Node(int data) {
8        this->data = data;
9        next = nullptr;
10    }
11};
12
13// Linked list class
14class LinkedList {
15public:
16    Node* head;
17
18    LinkedList() {
19        head = nullptr;
20    }
21
22    // Function to insert a node at the end
23    void insert(int data) {
24        Node* newNode = new Node(data);
25        if (head == nullptr) {
26            head = newNode;
27        } else {
28            Node* current = head;
29            while (current->next != nullptr) {
30                current = current->next;
31            }
32            current->next = newNode;
33        }
34    }
35
36    // Function to delete a node from the linked list
37    void deleteNode(int value) {
38        Node* current = head;
39        Node* previous = nullptr;
40
41        // Iterate through the list to find the node to delete
42        while (current != nullptr) {
43            if (current->data == value) {
44                // If the node to delete is the head
45                if (current == head) {
46                    head = current->next;
47                } else {
48                    previous->next = current->next;
49                }
50                delete current;
51                return;
52            }
53
54            previous = current;
55            current = current->next;
56        }
57
58        cout << "Node with value " << value << " not found" << endl;
59    }
60
61    // Function to print the linked list
62    void printList() {
63        Node* current = head;
64        while (current != nullptr) {
65            cout << current->data << " ";
66            current = current->next;
67        }
68        cout << endl;
69    }
70};
71
72int main() {
73    LinkedList list;
74
75    // Insert nodes
76    list.insert(1);
77    list.insert(2);
78    list.insert(3);
79    list.insert(4);
80
81    // Print initial list
82    cout << "Initial List: ";
83    list.printList();
84
85    // Delete a node
86    int value = 3;
87    cout << "Deleting Node with value " << value << "..." << endl;
88    list.deleteNode(value);
89
90    // Print updated list
91    cout << "Updated List: ";
92    list.printList();
93
94    return 0;
95}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment