且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Delete Node in a Linked List

更新时间:2022-07-06 19:15:18

Well, this problem is just a trick. In fact, we cannot really delete the given node, but just delete its next node after copying the data of the next node to it.

The code is as follows.

1 class Solution {
2 public:
3     void deleteNode(ListNode* node) {
4         ListNode* next = node -> next;
5         node -> val = next -> val;
6         node -> next = next -> next;
7     }
8 };

If you are familiar with pointer operations, the code can be even shorter, just 1-line!

1 class Solution {
2 public:
3     void deleteNode(ListNode* node) {
4         *node = *node -> next;
5     }
6 };

This link shares solutions to this problem in all supported languages of the LeetCode OJ. You may take a look at it and appreciate the appetite of each language.