Java 在LinkedList的索引处插入

Java 在LinkedList的索引处插入,java,linked-list,Java,Linked List,嗨,我有这个方法在LinkedList的任何索引中插入一个元素,但是,输出中没有显示新元素,我错过了什么谢谢! 我在下面展示了部分代码,非常感谢您的帮助 public class LinkedList<E extends Comparable<E>> implements Iterable<E> { // instance data members of list private Node head; // reference to the f

嗨,我有这个方法在LinkedList的任何索引中插入一个元素,但是,输出中没有显示新元素,我错过了什么谢谢! 我在下面展示了部分代码,非常感谢您的帮助

public class LinkedList<E extends Comparable<E>> implements Iterable<E>
{
    // instance data members of list
    private Node head; // reference to the first node
    private int N;     // number of elements stored in the list

    private class Node
    {
        // instance data members of Node
        public E item;
        public Node next;

        // constructors for Node
        public Node()
        {
            item = null;  next = null;
        }

        public Node(E e, Node ptr)
        {
            item = e;  next = ptr;
        }
    }// end class Node

    public void insertAfter(int k, E e){
        if (k < 0 || k >= size()){
            throw new IndexOutOfBoundsException();}
        Node temp=new Node();
        temp.item=e;
        int index=k-1;
        Node current=head;
        for (int i=0; i<=N; N++){
            if (i==index){
                temp.next=current.next;
                current.next=temp;
            }
        }
        ++N;  
    }
公共类LinkedList实现了Iterable
{
//列表的实例数据成员
私有节点头;//对第一个节点的引用
private int N;//列表中存储的元素数
私有类节点
{
//节点的实例数据成员
公共电子项目;
公共节点下一步;
//节点的构造函数
公共节点()
{
item=null;next=null;
}
公共节点(E,节点ptr)
{
项目=e;下一个=ptr;
}
}//端类节点
公共无效插入符(int k,E){
如果(k<0 | | k>=size()){
抛出新的IndexOutOfBoundsException();}
节点温度=新节点();
温度项目=e;
int指数=k-1;
节点电流=头;

对于(int i=0;i它看起来像是在增加一个实例变量
N

试试这个

public void insertAfter(int k, E e){
    if (k < 0 || k >= size()){
        throw new IndexOutOfBoundsException();}
    Node temp=new Node();
    temp.item=e;
    int index=k-1;
    Node current=head;
    for (int i=0; current != null && i<N; i++){
        if (i==index){
            temp.next=current.next;
            current.next=temp;
        } else {
            current = current.next;
        }
    }
    ++N;  
}
public void insertAfter(int k,E){
如果(k<0 | | k>=size()){
抛出新的IndexOutOfBoundsException();}
节点温度=新节点();
温度项目=e;
int指数=k-1;
节点电流=头;

对于(int i=0;current!=null&&i您不会在列表中移动当前元素。您循环整数索引,但不会将指针移动到当前节点。因此在循环中current始终是链接列表的标题。 你需要这样做:

for (int i=0; i<=N; N++)
        if (i==index){
            temp.next=current.next;
            current.next=temp;
        }else{
         current=current.next;
       }

for(inti=0;我太感谢你了!我怎么会错过这个……哈哈