• 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.


    题目标签:Linked List

      题目给了我们一个点,让我们在链表中删除这个点。

      一般来说,要删除一个点,首先想到的是 把这个点的前面一个点 直接 链接到 这个点的 后面一个点 就可以了。

      但是这一题只给了我们要删除的这个点(不会是最后一个点),所以回不到上一个点。

      只要改变一下想法,用下一个点的val 复制到这一个点就可以了,然后把这一个点 链接到 下下个点就可以了。

    Java Solution:

    Runtime beats 9.42% 

    完成日期:06/12/2017

    关键词:singly-linked list

    关键点:把下一个点的val 复制到这一个点

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution 
    10 {
    11     public void deleteNode(ListNode node) 
    12     {
    13         // copy next node val into this node, then link this node to next next node
    14         ListNode nextNode = node.next;
    15         node.val = nextNode.val;
    16         node.next = nextNode.next;
    17         
    18         nextNode.next = null; // unlink nextNode to null
    19         
    20     }
    21 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    Caffe--solver.prototxt配置文件 参数设置及含义
    关于KMP算法理解(快速字符串匹配)
    Lintcode--004(最小子串覆盖)
    Lintcode--003(乱序字符串)
    Lintcode--002(两个字符串是变位词)
    Lintcode--001(比较字符串)
    闭包的应用实例
    JavaScript完整性检查
    null和undefined相等比较
    JavaScript逻辑运算符(操作数运算符)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7986196.html
Copyright © 2020-2023  润新知