In the generate method, a reference to the current Node is stored in the variable ref. It is necessary to solve the problem without using this variable by adding a while loop to the for loop. Initial task:

public class StringLinkedListTest { public static void main(String[] args) { Node ref = generate(9); while (ref != null){ System.out.print(" " + ref.value); ref = ref.next; } } public static Node generate(int max){ Node result = new Node(max, null); Node ref = result; for (int k = max; k > 0; k--){ ref.next = new Node(k - 1, null); ref = ref.next; } return result; } } public class Node { int value; Node next; public Node(int value, Node next) { this.value = value; this.next = next; } } 

I try to solve it, but my code returns 9 instead of 9,8,7,6,5,4,3,2,1,0. The problem occurs during the transition to the nested Node. Tell me, how can I fix it here so that in while the transition to the next Node is made?

 public static Node generate(int max){ Node result = new Node(max, null); for (int k = max; k > 0; k--){ int copy = max; while (copy != 0){ if (result.next == null){ result.next = new Node(copy - 1, null); break; } copy--; } result.next = result.next.next; } return result; } 
  • I see no point in your generate function with two cycles. :) - Vlad from Moscow

1 answer 1

So it should be?

 public static Node generate(int max) { int count = 0; Node result = null; while(max >= count){ result = new Node(count++, result); } return result; } 

Addition to the comment:

 public static Node generate(int max) { Node result = new Node(max, null); for (int k = max; k > 0; k--) { Node ref = result; while (ref.next != null) { ref = ref.next; } ref.next = new Node(k - 1, null); } return result; } 
  • Not really, the point is that the creation of objects goes in order: with value = 8, then = 7, and so on. And you need to do without the variable of the current Node. Those. The every while should go through the already created objects, starting with the object with value = 9. - vips
  • Completed the answer as you said. But without the current variable Node, I have no idea how to do this. - MrFylypenko
  • Thank you very much. However, the author of the course claims that it is possible to do this in a while, which only refers to the end, i.e. on result. - vips
  • The first variant of my answer does just that, starts from the end (ie, from "0") and returns the beginning of the linked list. But to do as in the question: the создание объектов в порядке с 8... not from scratch (from the beginning) and to run through the list every time - this cannot be done without an additional variable, or the question is not correct. - MrFylypenko
  • The task is taken from here youtube.com/… - time 2:15 - vips