69. 在O(1)时间删除链表节点

本文详细探讨了在链表中删除节点的各种情况,包括链表为空、删除头节点、删除尾节点以及删除中间节点的处理方法。特别关注如何在O(1)时间复杂度下进行操作,提供了一种将待删节点改造为其后继节点的方法。

对于删除链表节点需要考虑的问题

  1. 链表为空时?
  2. 删除头节点时?
  3. 删除尾节点时?

要在O(1){O(1)}O(1)的时间复杂度内删除节点,那只能采用特殊办法了

  1. 对于头节点,很容易完成,因为它没有前驱
  2. 对于中间节点,只能是把待删除节点改造成其后继节点,然后删除后继节点了,这样值是相等的,但是确实不是同一个节点
  3. 对于尾节点,可能就需要从头遍历了
/**
 * @Classname Solution
 * @Description TODO
 * @Date 2019/12/23 8:21
 * @Author Cheng
 */
public class Solution {
    public static void main(String[] args) {
        ArrayList<ListNode> nodes = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ListNode node = new ListNode(i);
            if (i > 0) {
                nodes.get(i-1).next = node;
            }
            nodes.add(node);
        }
        ListNode head = nodes.get(0);
        ListNode node = nodes.get(9);
        head = deleteNode(head,node);
        showLinkedList(head);
    }

    public static void showLinkedList(ListNode head) {
        StringBuilder ret = new StringBuilder();
        while (head != null) {
            ret.append(head.val);
            if(head.next!=null)
                ret.append("-->");
            head = head.next;
        }
        System.out.println(ret.toString());
    }
    public static ListNode deleteNode(ListNode head, ListNode node) {
        //链表为空或node无效
        if (head == null || node == null) return null;
        // 删除头节点
        if (head == node) {
            ListNode next = head.next;
            head.next = null;
            head = next;
        }
        // 删除尾节点
        else if (node.next == null) {
            ListNode cur = head;
            while (cur.next != node) {
                cur = cur.next;
            }
            ListNode next = node.next;
            node.next = null;
            cur.next = next;
        }
        // 正常删除节点
        else {
            ListNode next = node.next;
            node.val = next.val;
            node.next = next.next;
            next.next = null;
        }
        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山与长生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值