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

    • Total Accepted: 133535
    • Total Submissions: 292943
    • Difficulty: Easy
    • Contributors: Admin

    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.

    Subscribe to see which companies asked this question.

    分析


    方法一

    最笨的办法,把后面值挨个复制到千面
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Solution {
    public:
        void deleteNode(ListNode* node) {
            //consider shift all the nodes' values in the right position of given node
             
            ListNode * pre = NULL;
            while(node->next){
                pre = node;
                node->val = node->next->val;
                node = node->next;
            }
            pre->next = NULL;
        }
    };

    方法二

    1
    2
    3
    4
    5
    6
    7
    8
    class Solution {
    public:
        void deleteNode(ListNode* node) {
            ListNode* next = node->next;
            *node = *node->next;
            delete next;
        }
    };


     




  • 相关阅读:
    冒泡排序
    pdo 单例类
    php 事物处理
    支付宝支付
    反向代理和负载均衡
    execl导出
    网络层
    OSI 7层 TCP/IP 4层 综合5层
    面试总结
    CMD AMD
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/ed408c0b135998277e5404ed8791c84a.html
Copyright © 2011-2022 走看看