java删除单链表中值为key的第一节点,删除单链表中值为key的所有节点

删除单链表中值为key的第一个节点

//删除值为key的节点
    public void removeKey(int key) {
        //判断链表是否为空
        if (this.head == null) {
            System.out.println("链表为空");
            return;
        }
        //删除的为头结点
        if (this.head.data == key) {
            this.head = this.head.next;
            return;
        }
        //找key的前驱节点
        Node index = findKeyIndex(key);
        if (index == null) {
            System.out.println("该节点的前驱不存在");
            return;
        }
        index.next = index.next.next;
    }

    //找key的前驱节点
    public Node findKeyIndex(int key) {
        if (this.head == null) {
            System.out.println("链表为空");
            return null;
        }
        Node cur = this.head;
        while (cur.next != null) {
            if (cur.next.data == key) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }

删除单链表中值为key的所有节点

//删除所有值为key的节点
    public void removeAllKey(int key) {
        if (this.head == null) {
            return;
        }
        Node prev = this.head;//当前节点的前一个节点
        Node cur = this.head.next;//当前节点
        while (cur != null) {
            //当前节点的值为key
            if (cur.data == key) {
                prev.next = cur.next;
                cur = cur.next;
            } else {
                //当前节点的值不为key
                prev = cur;
                cur = cur.next;
            }
        }
        //判断头节点的值是否为key
        if (this.head.data == key) {
            this.head = this.head.next;
        }
    }

清空链表

//清空链表
    public void clean() {
        this.head = null;
    }

单链表其他操作,增删查改完整代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值