剑指offer第2版18题:删除链表结点

本文介绍了一种在O(1)时间内删除单向链表中指定节点的方法。通过两种不同的策略实现了这一目标:当待删除节点有后续节点时,采用值复制的方式;当待删除节点为链表尾部节点时,则需遍历找到其前驱节点并调整链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小渣渣的算法学习笔记:2018秋招备战


数据结构类算法总结:链表


1.题目描述:

O(1)时间内删除链表节点。
给定单向链表头指针和一个结点指针,定义一个函数在O(1)时间内删除该节点。

2.代码实现:

public class Solution69_18 {
    private static class ListNode {
        int value;
        ListNode next = null;
        ListNode(int val) {
            this.value = val;
        }
    }

    public static void main(String[] args) {
        Solution69_18 s = new Solution69_18();
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;

        s.deleteNode01(l1,l3);
        s.deleteNode02(l1,l1);

        s.printListNode(l1);
    }

    public ListNode deleteNode01(ListNode head, ListNode node) {
        // 检查空
        if (node == null) {
            throw new RuntimeException();
        }
        ListNode next = node.next;
        if (next != null) {
            // 有下一个节点的情况:复制覆盖
            node.value = next.value;
            node.next = next.next;
            // 没有下一个节点的情况
        } else {
            ListNode previous = null;
            ListNode current = head;
            while (current != null) {
                if (current == node) {
                    // 前一个为空,要删除的节点即是第一个头结点
                    if (previous == null) {
                        head = null;
                    } else {
                        // 前一个不为空,则将next置为null即可
                        previous.next = null;
                    }
                }
                previous = current;
                current = current.next;
            }
        }
        return head;
    }

    public void printListNode(ListNode pHead){
        while(pHead.next!=null){
            System.out.print(pHead.value+" ");
            pHead = pHead.next;
        }
        System.out.print(pHead.value+" ");
    }

    public void deleteNode02(ListNode pHead,ListNode pDel){
        if(pHead == null || pDel == null) return;
        //要删除的结点不是尾结点
        if(pDel.next != null){
            ListNode temp = pDel.next;
            pDel.value = temp.value;
            pDel.next = temp.next;
        }
        //只有一个结点
        else if(pHead == pDel){
            pDel = null;
            pHead = null;
        }
        //链表中多个节点,删除尾结点;需要从链表的头结点开始顺序遍历尾结点的前序结点,完成删除操作
        else{
            ListNode temp = pHead;
            while(temp.next!=pDel){
                temp = temp.next;
            }
            temp.next = null;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值