The insert method adds an element to a specific position, shifting the rest to the right. Here is my code:

public void insert(Object data, int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(Integer.toString(index)); } Node node = new Node(null,data); Node cur = head ; // ссылка на начало if (index == 0) { if (size == 0) { head = node; size = 1; } else { node.next = head; head = node; size++; } } else{ for(int i = 0 ; i<index && cur.next!=null ; i++) // находим элемент с этим индексом cur = cur.next ; node.next = cur ; // говорим , что после вставляемого элемента, будет cur size++; } } 

But I assume that the problem is that I did not write after which element the inserted (new) element will be located. How can I do that?

    1 answer 1

    Everything is simple LinkedList is an implementation of the linked list algorithm. It has a standard method:

     void add(int index, E element) 

    which: Inserts the specified element at the specified position in this list. (Adds any to their indices).

    According to the specification, he already inserts it with a shift of all elements in the rights

    If you want to write your own insertion method then: The LinkedList class includes a static inner class Entry, with which new elements are created.

     private static class Entry<E>{ E element; Entry<E> next; Entry<E> prev; Entry(E element, Entry<E> next, Entry<E> prev){ this.element = element; this.next = next; this.prev = prev; } } 

    To add a new item to LinkedList, you need to perform two iterations:

    1. create an instance of the class Entry;
    2. redefine pointers to the previous and next item.