博文中会简要介绍Leetcode P0237题目分析及解题思路。
“Delete Node in a Linked List”一道很简单且没有什么价值的题目。题目本身很简单,通过向前覆盖即可实现删除操作。但不得不吐槽的是,我们在删除结点是考虑的是指针修改和连接的相关操作,而这道题则是通过类似数组中删除元素那样通过向前覆盖来实现删除。也就是本质上其实不是结点的删除,而是结点中值的修改罢了。将数组的操作应用到链表上,实则没有什么意义。
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.
It is guaranteed that the node to be deleted is not a tail node in the list.
以下是Java的题解代码实现。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
ListNode prev = null, curr = node, post = node.next;
while (post != null) {
curr.val = post.val;
prev = curr;
curr = post;
post = post.next;
}
prev.next = null;
}
}
以下是C++的题解代码实现。
/**
* 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) {
ListNode *prev = nullptr, *curr = node, *post = node->next;
while (post) {
curr->val = post->val;
prev = curr;
curr = post;
post = post->next;
}
delete curr;
prev->next = nullptr;
}
};