I have two practice problems that I'm having trouble understanding. For # 1, the answer is that the list is printed in reverse, can anyone explain this to me? Also #7, why does the list begin to go backwards once it reaches the null? If anyone can provide some quick explanations it would be greatly appreciated, thanks!
1) What does the following function do for a given Linked List if we call it with the head node?
void method1(Node<T> node) {
if(node == null)
return;
method1(node.getNext());
System.out.println(node.getData().toString());
}
a. Prints the nodes of the linked list.
b. Prints the nodes of the linked list in reverse order.
c. Prints alternate nodes of the linked list.
d. Prints alternate nodes in reverse order.
Answer
b. Prints the nodes of the linked list in reverse order.
7) What is this method going to print, if we call it with the headnode of the linked list 1 → 2 → 3 → 4 → 5 → 6 ?
void method1(Node<Integer> node) {
if (node == null)
return;
System.out.printf(“%d ”, node.getData());
if (node.getNext() != null)
method1(node.getNext().getNext());
System.out.printf(“%d ”, node.getData());
}
a. 1 6 2 5 3 4
b. 1 3 5 6 4 2
c. 1 3 5 1 3 5
d. 1 3 5 5 3 1
Answer
c. 1 3 5 5 3 1
System.out.println(...)gets called before the method returns. Try to think the sequence of steps the program will take for a given input list.