To delete a node from a linked list, we need to update the pointers of the previous and next nodes to bypass the node to be deleted.
Here's the C++ code to delete a node from a linked list:
1#include <iostream>
2using namespace std;
3
4// Linked List Node
5struct Node {
6 int data;
7 Node* next;
8 Node(int d) : data(d), next(nullptr) {}
9};
10
11// Function to delete a node from a linked list
12void deleteNode(Node* node) {
13 if (node == nullptr || node->next == nullptr) {
14 return;
15 }
16
17 Node* nextNode = node->next;
18 node->data = nextNode->data;
19 node->next = nextNode->next;
20 delete nextNode;
21}
22
23int main() {
24 // Create a linked list
25 Node* head = newNode(1);
26 head->next = newNode(2);
27 head->next->next = newNode(3);
28 head->next->next->next = newNode(4);
29
30 // Delete a node
31 deleteNode(head->next->next);
32
33 // Print the modified linked list
34 Node* current = head;
35 while (current != nullptr) {
36 cout << current->data << " ";
37 current = current->next;
38 }
39
40 return 0;
41}
In this code, we first check if the node to be deleted is nullptr
or its next node is nullptr
. If either of these conditions is true, we return from the function since it is not possible to delete the node.
Next, we create a pointer nextNode
and assign it the value of the next node of the node to be deleted. Then, we update the data of the current node with the data of the next node, and update the next
pointer of the current node to point to the next node of the next node. Finally, we delete the memory allocated for the next node.
Let's test this code with a sample linked list and delete a node from it.
xxxxxxxxxx
}
using namespace std;
// Linked List Node
struct Node {
int data;
Node* next;
Node(int d) : data(d), next(nullptr) {}
};
// Function to delete a node from a linked list
void deleteNode(Node* node) {
if (node == nullptr || node->next == nullptr) {
return;
}
Node* nextNode = node->next;
node->data = nextNode->data;
node->next = nextNode->next;
delete nextNode;
}
int main() {
// Create a linked list
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);