LinkedList底层简化版实现

public class MyLinkedList {

    //MyLinkedList存储数据个数
    int size;
    //首节点
    Node first;
    //尾节点
    Node last;

    //添加数据
    public boolean add(Object o) {
        Node node = new Node(last, o, null);
        //如果尾节点为空,即MyLinkedList没有数据把添加的数据设置为首节点否则把已有的尾节点的next指向该数据
        if (last == null) {
            first = node;
        } else {
            last.next = node;   
        }
        //新添加的数据设置为节点之后,把该节点设置为尾节点
        last = node;
        //长度++
        size++;

        return true;
    }

    //删除数据
    public Object remove(int index) {
        //通过下标获得要删除节点获取其中数据,值、前一个节点、后一个节点
        Node node = node(index);
        Object value = node.value;
        Node pro = node.pro;
        Node next = node.next;
        //验证下标合法性
        if (index >= 0 && index < size) {
            //如果该节点没有前一个节点,即该节点为首节点,将该节点的下一个节点设置为首节点
            if (pro == null) {
                next.pro = null;
                node.next = null;
                first = next;
            }
            //如果该节点没有下一个节点,即该节点为为节点,将该节点的上一个节点设置为尾节点
            else if (next == null) {
                pro.next = null;
                node.pro = null;
                last = pro;
            }
            //如果该节点既不是首节点也不是尾节点,将该节点的上一个节点的next指向该节点的下一个节点,将该节点的下一个节点的pro指向该节点的上一个节点
            else{
                pro.next = next;
                next.pro = pro;
            }
            //最后将该节点置空,长度减一
            node = null;
            size--;

        } else {
            System.out.println("不存在该序号元素");
        }
        return value;
    }

    //修改
    public void set(int index, Object o) {
        if (index >= 0 && index < size) {
            Node node = node(index);
            node.value = o;
        }else {
            System.out.println("不存在该序号元素");
        }
    }

    public Object get(int index){
        return node(index).value;
    }

    //查询
    public Node node(int index) {
        //当查询的下标小于长度一半时从尾部从头部遍历,否则从尾部遍历
        if (index < (size >> 1)) {
            Node x = first;
            for (int i = 0; i < index; i++) {
                x = x.next;
            }
            return x;
        } else {
            Node x = last;
            for (int i = size - 1; i > index; i--) {
                x = x.pro;
            }
            return x;
        }
    }

    class Node {
        Object value;
        Node pro;
        Node next;

        public Node(Node pro, Object value, Node next) {
            super();
            this.value = value;
            this.pro = pro;
            this.next = next;
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值