会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132885个问题
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 19321楼
JAVA 全系列/第一阶段:JAVA 快速入门/变量、数据类型、运算符 19322楼
JAVA 全系列/第四阶段:网页编程和设计/Jquery(旧) 19323楼
Python 全系列/第一阶段:Python入门/Python入门(动画版) 19324楼

老师,这是我创建的一个在指定位置添加元素


// 校验index合法性  0<=index<=size
private void checkIndex02(int index){
    if(!(index >=0 && index <= this.size)){
        throw new IndexOutOfBoundsException("index:"+index+"  size:"+size);
    }
}

// 指定位置添加元素
private void LinkIndex(int index,E element){
    // 检验index合法性 0=<index<=size
    this.checkIndex02(index);
    // 如果index == size 元素添加至尾部
    if(index == size){
        this.LinkLast(element);
    } else if(index == 0){ // index==0 元素添加至头部
        this.LinkFirst(element);
    } else {
        Node<E> node =  this.getNode(index); // 获取指定位置节点
        Node<E> temp = new Node<>(node.prev,element,node); // 创建新节点,位于node前面
        node.prev = temp;
        node.prev.next = temp; //node节点的前一节点指向temp
    }
    // 记录元素个数
    this.size++;
}

// 将节点对象元素添加到双向链表头部
private void LinkFirst(E element){
    Node<E> head = this.head;
    Node<E> node = new Node<>(null,element,head);
    this.head = node;
    if(head == null){
        this.tail = node; 
    } else { 
        head.prev = node;
    }
    // 记录元素个数
    this.size++;
}

// 将节点对象元素添加到双向链表尾部 LinkLast
private void LinkLast(E element){
    // 获取尾节点
    Node<E> t = this.tail;
    Node<E> node = new Node<>(t,element,null);
    this.tail = node;
    if(t == null){ 
        this.head = node;
    } else { 
        t.next = node; 
    }
    // 记录元素个数
    this.size++;
}
// 指定位置添加元素
public void addIndex(int index,E element){
    this.LinkIndex(index,element);

}

测试后运行时正常的,您帮我看看有没有问题,谢谢

JAVA 全系列/第二阶段:JAVA 基础深化和提高/数据结构 19325楼
JAVA 全系列/第四阶段:网页编程和设计/Jquery(旧) 19326楼
JAVA 全系列/第四阶段:网页编程和设计/Jquery(旧) 19327楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 19328楼
JAVA 全系列/第八阶段:Linux入门到实战/Maven 19330楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 19331楼
JAVA 全系列/第一阶段:JAVA 快速入门/JAVA入门和背景知识 19332楼
JAVA 全系列/第四阶段:网页编程和设计/Jquery(旧) 19333楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 19334楼
JAVA 全系列/预科阶段:职业规划/学习方法/JAVA 技术体系介绍和学习方法 19335楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637