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