美文网首页剑指offer——Java实现
面试题13:在O(1)时间删除链表结点

面试题13:在O(1)时间删除链表结点

作者: _minimal | 来源:发表于2016-10-07 21:27 被阅读13次

题目描述

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.

代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void deleteNode(ListNode node) {
        //先让该结点的值等于下一个结点的值12345->12445
        node.val = node.next.val;
        //再把下一个结点删除12445->1245
        node.next = node.next.next;
    }
}

主要思路

很简单,只需要把当前结点的值复制为下一个结点的值,然后删除下一个结点,就相当于把当前结点删除了

相关文章

网友评论

    本文标题:面试题13:在O(1)时间删除链表结点

    本文链接:https://www.haomeiwen.com/subject/neayyttx.html