zoukankan      html  css  js  c++  java
  • 【LeetCode】237. Delete Node in a Linked List

    题目:

    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. 比如我们这里要删除的节点是节点2;
    2. 首先创建一个指向节点3的指针,然后将节点2赋值为节点3,此时的链表状态如第二行所示;
    3. 最后别忘记将节点3删除(通过删除之前创建的指针)。

    代码:

    /**
     * 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 *next = node->next;
            *node = *next;
            delete next;
        }
    };
  • 相关阅读:
    相关书籍下载2
    神奇的null和undefined
    相关书籍下载1
    微信小程序之for循环
    渐变(Gradients)
    模拟今日头条顶部导航菜单
    网格布局之相关特性
    网格布局之合并单元格
    网格布局
    Linux常用命令
  • 原文地址:https://www.cnblogs.com/jdneo/p/4737112.html
Copyright © 2011-2022 走看看