I have a method. I transfer to it the name of the new data object and its future number num . I have a single linked list.

My idea is this: to find the predecessor by number, extract the link to the child from it, specify the link to the new object instead of it and place the extracted link in it. The question is how to extract the link and pass it on? And in general, can this be done?

 public static void addTo(String data, int num) { int count = 0; Node1 elem = new Node1(); elem.data = data; Node1 temp=head; while (count < num) { if (num - count == 1){ //temp=temp.next; //count ++; } //else } } 
  • why not just use the built-in insert methods in the List? - Oleg
  • What methods? And How? - Alexander
  • Google says that there is a method add(int index, T element); - Oleg
  • So you can do it, but why comment the code? - Roman C

1 answer 1

Scrolling through the list, reaching the desired item and increasing the index counter. After the end of the cycle you will have a link.

 public static void addTo(String data, int num) { int count = 0; Node1 elem = new Node1(); elem.data = data; Node1 temp=head; Node1 ref = temp; while (count < num && temp != null) { // прокручиваем список пока не дойдем до num ref = temp; // сохраняем ссылку на предыдущий элемент temp=temp.next; // двигаемся к следующему элементу count ++; } if (ref == null) { head = elem; } else { Node1 tmp = ref.next; ref.next = elem; elem.next = tmp; } }