数据结构(三)——LinkedList与链表(下)

承接上文:

1.删除第一次出现关键字为key的节点

public void remove(int key){
         if(this.head == null){//头结点就是空
            return;
         }
        if(this.head.val == key){//删除头结点
            this.head = this.head.next;
            return;
        }
        ListNode cur = findIndexSubOne(key);//找前驱
        if(cur == null){
            System.out.println("没有你要找的数字!");
            return;
        }
        ListNode del = cur.next;
        cur.next = del.next;//核心代码!!!
    }
 
    //找出现key的前驱节点 cur
    private ListNode findProverOfkey(int key){
        ListNode cur = this.head;
        while (cur.next != null){
            //为什么是cur.next 因为我们需要提前判断下一个节点
            //  如果为空 说明后面已经没有我们要找到的元素了
            if(cur.next.val == key){
                return cur;
            }
            cur = cur.next;
        }
        return null;//表示没找到要删除的元素

2.删除所有val==key的节点


 public void removeAllKey(int key){
        if(this.head == null){
            return;
        }
        ListNode cur = this.head.next;
        ListNode prev = this.head;
        while (cur!=null){
           if(cur.val == key){
               prev.next = cur.next;
               cur = cur.next;
           }else{
               prev = cur;
               cur = cur.next;
           }
        }
        if(this.head.val == key){
            this.head =this.head.next;
        }
    }

3.清除

public void clear() {
        this.head = null;
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值