Java 数据结构:单向链表(带烧饼版)

复制代码
import java.util.function.Consumer;
public class SinglyLinkedList {//烧饼版
    private Node head = new Node(666,null);//头指针指向哨兵结点

    private static class Node {//定义结点

        int value;
        Node next;

        public  Node(int value, Node next) {//定义实例变量
            this.value = value;
            this.next = next;
        }
    }//定义结点

    public void addFirst(int value) {//添加头结点
        insert(0,value);
    }
    public void loop(Consumer<Integer>consumer){//接受数据值并延长链表
        Node p = head.next;
        while (p != null){
            consumer.accept(p.value);
            p = p.next;
        }
    }
    private Node findLast(){//连接尾结点
        Node p;
        for (p = head;p.next != null;p = p.next){//结点指向下一结点

        }
        return p;
    }
    public void addLast(int value){//尾部添加
        Node last = findLast();//为尾结点添加指向新建结点的next值
        if (last == null){
            addFirst(value);
            return;
        }
        last.next = new Node(value,null);//添加新节点
    }
    private Node findNode(int index){//找索引
        int i = -1;
        for (Node p = head; p != null; p = p.next,i++){
            if (i == index){
                return p;
            }
        }
        return null;
    }
    public void printList(){
        Node p = head.next;
        while (p != null){
            System.out.println(p.value);
            p = p.next;
        }
        System.out.println();
    }
    private static IllegalArgumentException illegalIndex(int index) {
        return new IllegalArgumentException(
                String.format("index [%d] 不合法%n", index));
    }
    public int get(int index){
        Node node = findNode(index);
        if (node == null){
            throw illegalIndex(index);
        }
        return node.value;
    }
    public void insert(int index,int value){
        Node prev = findNode(index - 1);//找到上一结点
        if (prev == null){//头结点插入
           throw illegalIndex(index);}
        prev.next = new Node(value,prev.next);
    }
    public void removeFirst(){
        remove(0);
    }
    public void remove(int index){
        Node prev = findNode(index - 1);//上一个结点
        if (prev == null){
            throw illegalIndex(index);
        }
        Node removed = prev.next;  //被删除的结点
        if (removed == null){
            throw illegalIndex(index);
        }
        prev.next = removed.next;
    }
}
复制代码

 

posted @   真绪无码  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示