leetcode解题: Delete Node in a Linked List (237)

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

解法1:O(1) Time

由于只给了当前node的指针,那么没办法得到前面一个节点的信息。只能换种思考方式。我们可以将下一个节点的数值拷贝过来然后删除下一个节点就可以。

C++

要注意的是要删除下一个节点指针对应的object,否则会造成leak

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
if (node == NULL || node-> next == NULL) {
return;
}
node->val = node->next->val;
ListNode* p = node->next;
node->next = node->next->next;
delete p;
}
};

Java

1