[LeetCode] Delete Node in a Linked List

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.

posted @ 2015-07-15 13:44  jianchao-li  阅读(262)  评论(0编辑  收藏  举报