java - 在 LinkedList 的索引处插入

标签 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 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;  
    }

最佳答案

您没有在列表中移动当前元素。您循环整数索引,但不将指针移动到当前节点。所以在循环中current始终是链表的头部。 你需要这样做:

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

这样,当您添加元素时,您将处于正确的位置。否则您将无法将其插入到第一个位置。

关于java - 在 LinkedList 的索引处插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30118157/

相关文章:

java - Spring data findone 未获取最新数据

java - 获取 TextView 的高度

performance - 列出缓存行为

java - 了解关于引用队列的虚引用与弱引用

java - 如何模拟 URL 连接

java - eclipse egit 工作目录 vs jenkins 和 git 方式

c - 由 2 个结构组成的链表。接入节点

C 链表 - 返回第一个堆栈项

c - 无法从链表中删除最低值

c - 使用指向指针的指针有什么意义?