(有头)链表的实现(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;
    }
相关推荐
乐hh2 小时前
Hadoop 3.3.5 + Flink 1.15.3 集群完整部署手册(3节点标准版)
java·大数据·hadoop·hdfs·zookeeper·flink·yarn
SunnyDays10112 小时前
如何使用 Java 实现自动删除 Word 文档中的空白页或指定页
java·删除 word 文档空白页·删除 word 文档页面
༄天M宇ༀ2 小时前
E10: e-builder 低代码构建平台接口管理(E9建模版)
java·前端·spring·servlet·reactjs
!停2 小时前
数据结构算法—归并排序
数据结构·算法
蜜獾云2 小时前
java 异步编程
java·开发语言
xin^_^2 小时前
java基础学习
java·开发语言·python
yttandb2 小时前
数据库的设计
java·数据库
zhouping@2 小时前
JAVA的学习笔记day05
java·笔记·学习
luckyzlb2 小时前
02-kafka(01润色版)
java·中间件·kafka