✨hello,进来的小伙伴们,你们好耶!✨
⛴️⛴️系列专栏:【数据结构与算法】
⛵⛵作者简介:一名大三科班在读的编程小白,星夜漫长,你我同行!
🚀🚀本篇内容:LinkedList的知识点补充,链表面试题分析!
🚲🚲码云存放仓库gitee:https://gitee.com/king-zhou-of-java/java-se.git
承接上篇:
🚐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;
- }
🚎运行结果:
