LeetCode C++ 237. Delete Node in a Linked List【链表】简单
发布日期:2021-07-01 02:50:04 浏览次数:2 分类:技术文章

本文共 2050 字,大约阅读时间需要 6 分钟。

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

Given linked list – head = [4,5,1,9] , which looks like following:

在这里插入图片描述
Example 1:

Input: head = [4,5,1,9], node = 5Output: [4,1,9]Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1Output: [4,5,9]Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Note:

  • The linked list will have at least two elements.
  • All of the nodes’ values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

题意:删除单链表中给定的某个非末尾的有效的结点。函数的唯一参数就是要删除的结点,函数不会返回任何值。


思路:如果要删除某个结点,就一定需要它之前的结点指针。这里只有要删除的结点指针,emmmm……,我们必须创造条件得到一个 pre 指针。由于给出的结点不是末尾结点,所以我们可以将 node->val 改为其后的结点的值,然后删除其后的结点。

代码很简单,三行就可以了:

class Solution {
public: void deleteNode(ListNode* node) {
node->val = node->next->val; ListNode *delNode = node->next; node->next = node->next->next; delete delNode; }};

效率:

执行用时:20 ms, 在所有 C++ 提交中击败了39.14% 的用户内存消耗:8.1 MB, 在所有 C++ 提交中击败了14.61% 的用户

拓展:如果只是单纯的给出一个链表中的结点 node ,要求在链表中删除它,就会出现许多问题。

  • 问题1:这种删除方式无法删除最后一个结点。比如,链表 1->2->3->null ,只知道删除结点 3 ,但是它作为最后的结点,没有下一个结点来代替它被删除,只有让结点 2next 指向 null 这一种方法,但是我们根本找不到结点 2 。又或者这样想,直接删除结点 3 使其在内存上的区域变成 null ,似乎相当于让结点 2next 指针指向 null ,起到删除结点 3 的效果?不可能null 是系统的一个特定区域,想要让结点 2next 指针指向 null ,就必须找到结点 2
  • 问题2:这种方式本质上不是删除 node 结点,而是改变 node 结点的值,然后删除它的下一个结点。在实际工程中使用这种方法可能造成大问题。比如,工程的某个结点代表很复杂的结构,结点值的复制比较复杂;或者禁止改变结点值;或者某个结点对外界有很多依赖等等。

具体的过程(用 Java 写的)见下面:

public class Node {
public int val; public Node next; public Node(int data) {
this.val = data; }}public void deleteNode(Node node) {
if (node == null) return; Node next = node.next; if (next == null) //是结尾结点 throw new RuntimeException("Can't remove last node."); node.val = next.val; node.next = next.next; next.next = null;}

转载地址:https://memcpy0.blog.csdn.net/article/details/108183127 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【算法学习】分块算法 莫队
下一篇:LeetCode C++ 24. Swap Nodes in Pairs【链表】中等

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年05月02日 09时01分37秒