LintCode 在O(1)时间复杂度删除链表节点

来源:互联网 发布:js bind 原理 编辑:程序博客网 时间:2024/05/16 08:50

题目

给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在O(1)时间复杂度删除该链表节点。样例Linked list is 1->2->3->4, and given node 3, delete the node in place 1->2->4

分析

  1. 知道当前的要删除节点的指针,直接将下个点的值复制到要删除的节点中。
  2. 如果删除的是最后一个节点,直接置空即可。

如下图:
这里写图片描述

代码

  //Definition for ListNode.  public class ListNode {      int val;     ListNode next;     ListNode(int val) {         this.val = val;         this.next = null;      }  }
public class Solution {    /**     * @param node: the node in the list should be deleted     * @return: nothing     */    public void deleteNode(ListNode node) {        // write your code here       if (node == null) {            return;        }        if (node.next == null) {            node = null;        }        ListNode next = node.next;        node.val = next.val;        node.next = next.next;    }}
原创粉丝点击