java 模拟 单链表

该文章描述了一个Java类`SingleLinkedList`,用于实现单链表的数据结构。类中包含了添加元素、按索引获取元素以及按索引删除元素的方法。添加元素时,会检查链表是否为空,然后将新节点添加到链表末尾。删除元素时,会根据索引位置分别处理首节点、尾节点和中间节点的删除情况。
摘要由CSDN通过智能技术生成
public class SingleLinkedList {
    private Node headNode;

    private Node lastNode;

    private int size;

    public void add(Object element) {
        Node node = new Node(element);
        if (headNode == null) {
            headNode = node;
            lastNode = node;
        } else {
            lastNode.next = node;
            lastNode = node;
        }
        size++;
    }


    public Object get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("数组越界");
        }
        return node(index).object;

    }

    /**
     * 根据序号删除元素
     *
     * @param index 序号
     */
    public void remove(int index) {
// 1.判断序号是否合法,合法取值范围:[0, size - 1]
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("序号不合法,index:" + index);
        }
// 2.处理删除节点在开头的情况
        if (index == 0) {
// 2.1 获得删除节点的后一个节点
            Node nextNode = headNode.next;
// 2.2 设置 headNode 的 next 值为 null
            headNode.next = null;
// 2.3 设置 nextNode 为单链表的首节点
            headNode = nextNode;
        }
// 3.处理删除节点在末尾的情况
        else if (index == size - 1) {
// 3.1 获得删除节点的前一个节点
            Node preNode = node(index - 1);
// 3.2 设置 preNode 的 next 值为 null
            preNode.next = null;
// 3.3 设置 preNode 为单链表的尾节点
            lastNode = preNode;
        }
// 4.处理删除节点在中间的情况
        else {
// 4.1 获得 index-1 所对应的节点对象
            Node preNode = node(index - 1);
// 4.2 获得 index+1 所对应的节点对象
            Node nextNode = preNode.next.next;
// 4.3 获得删除节点并设置 next 值为 null
            preNode.next.next = null;
// 4.4 设置 preNode 的 next 值为 nextNode
            preNode.next = nextNode;
        }
// 5.更新 size 的值
        size--;
    }

    private Node node(int index) {
        Node temp = headNode;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp;

    }


    public static class Node {
        private Object object;
        private Node next;

        public Node(Object object) {
            this.object = object;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值