I will also click LeetCode -- 2. Delete Node in a Linked List, leetcodelinked
This question means that you need to write a function to delete a node, but the last node is not in a single-chain table ...), only the node to be deleted. If the linked list is 1-> 2-> 3-> 4, you are given a third node with a value of 3, this linked list should be like this 1-> 2-> 4 after you call your function ......
It cannot delete the end node, so we need to determine the end node. To determine whether a node is the end node, you only need to determine whether node-> next is null. When we write the delete operation of the linked list, we will access the previous node of the node to be deleted, and then direct the next of the previous node to the next node of the node to be deleted, then release the node.
Here, we cannot access the previous node of the node to be deleted, so we cannot delete the node by simply changing the pointer. However, we can achieve the final effect by copying nodes. We will copy the value of the next node of the node to be deleted. At this time, the two nodes are exactly the same, and we release another node, which is equivalent to deleting a node. So the answer to this question is like this, although changing the pointer pointing is the easiest way ......
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution {10 public:11 void deleteNode(ListNode* node) {12 if (node == nullptr) {13 return;14 }15 if (node->next != nullptr){16 ListNode* t = node->next;17 node->val = node->next->val;18 node->next = node->next->next;19 delete t;20 }21 }22 };