嗨,我有这种方法可以在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;
}
最佳答案
您不会在列表中移动当前元素。您循环整数索引,但不要将指针移到当前节点。因此在回路中,电流始终是链表的开头。
您需要这样:
for (int i=0; i<=N; N++)
if (i==index){
temp.next=current.next;
current.next=temp;
}else{
current=current.next;
}
这样,当您添加元素时,您将处于适当的位置。否则,您将需要将其插入第一个位置。