(有头)链表的实现(Java)

一、初始化

java 复制代码
public class LinkedList {

    public class ListNode{
        int val = 0;
        ListNode next = null;
        public ListNode(int val){
            this.val = val;
            this.next = null;
        }
    }
    private ListNode head;
    private int size = 0;
    public LinkedList(){
        head = new ListNode(0);
        this.size = 0;
    }
}

二、头插

java 复制代码
    public void addFirst(int val){
        ListNode newNode = new ListNode(val);
        newNode.next = head.next;
        head.next = newNode;
        size++;
    }

三、尾插

java 复制代码
    public void addLast(int val){
        ListNode newNode = new ListNode(val);
        ListNode cur = head;
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = newNode;
        size++;
    }

四、指定位置插入(下标)

java 复制代码
    public void addIndex(int index, int val){
        if(index < 0 || index > size){
            return;
        }
        ListNode newNode = new ListNode(val);
        ListNode cur = head;
        while(index-- > 0){
            cur = cur.next;
        }
        newNode.next = cur.next;
        cur.next = newNode;
        size++;
    }

五、是否包含某个key

java 复制代码
    public boolean contains(int val){
        ListNode cur = head.next;
        while(cur != null){
            if(cur.val == val){
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

六、删除某个节点

java 复制代码
    public void remove(int val){
        ListNode cur = head.next;
        ListNode prev = head;
        while(cur != null){
            if(cur.val == val){
                prev.next = cur.next;
                size--;
                break;
            }
            prev = cur;
            cur = cur.next;
        }
    }

七、删除所有的key

java 复制代码
    public void removeAllKeys(int val){
        ListNode cur = head;
        while(cur.next != null){
            if(cur.next.val == val){
                cur.next = cur.next.next;
            }else{
                cur = cur.next;
            }
        }
    }

八、size、打印、清理

java 复制代码
    public int size(){
        return size;
    }
    public void display(){
        ListNode cur = head.next;
        while(cur != null){
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }
    public void clear(){
        head.next = null;
        size = 0;
    }
相关推荐
翊谦1 小时前
Java Agent开发 Milvus 向量数据库安装
java·数据库·milvus
晓晓hh1 小时前
JavaSE学习——迭代器
java·开发语言·学习
iFlyCai1 小时前
C语言中的指针
c语言·数据结构·算法
查古穆1 小时前
栈-有效的括号
java·数据结构·算法
汀、人工智能1 小时前
16 - 高级特性
数据结构·算法·数据库架构·图论·16 - 高级特性
Java面试题总结1 小时前
Spring - Bean 生命周期
java·spring·rpc
硅基诗人2 小时前
每日一道面试题 10:synchronized 与 ReentrantLock 的核心区别及生产环境如何选型?
java
014-code2 小时前
String.intern() 到底干了什么
java·开发语言·面试
摇滚侠2 小时前
JAVA 项目教程《苍穹外卖-12》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·vue.js·node.js
楚国的小隐士2 小时前
为什么说Rust是对自闭症谱系人士友好的编程语言?
java·rust·编程·对比·自闭症·自闭症谱系障碍·神经多样性