I'm having trouble writing a method that should accept a reference to a generic single-linked list and creating a test program to testing my method on a list of strings (print the list both in-order and reverse-order). I have already created a single-linked list called SinglyLinkedList.
Well if you think about recursion, you know you're going to be doing something over and over again. In this case we want to print a node over and over, but we want a different node each time.
Our first node we print should be the last in the list. That indicates to me an excellent base case.
void printReverse(Node node) {
if(node.next != null) { // we recurse every time unless we're on the last one
printReverse(node.next); // this says "do this to the next node first"
}
System.out.println(node.data); // we'll print out our node now
}
Consider if you had
1,2,3,4
You'd call print on the node with 1 in it. It would then say "I have a next node, print that". The 2 node also has a next node, so it defers to node 3. Node 3 still has a next node, so it defers to node 4 before printing. Node 4 is willing to print itself since it has no next node. Then it returns to where node 3 left off. Now node 3 can print and go back to where node 2 left off. It prints and goes to where node 1 left off. It prints and returns to the main function.
For in-order, call the output method before calling the function recurisvely.
void print(Node n)
{
if ( n != null )
{
System.out.println(n.value);
print(n.next);
}
}
For reverse, call the function first and the output.
void print(Node n)
{
if ( n != null )
{
print(n.next);
System.out.println(n.value);
}
}
I agree 100% with the answers above, for my implementation I could not get this to work without a helper class. My answer is only to expand on the answers above, in case others get compilation errors too.
public void printReverse()
{
printReverse(head);
}
private void printReverse(GNode<T> node)
{
if (node.next != null)
{
printReverse(node.next);
}
System.out.println(node.data);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.