简体   繁体   English

以相反顺序打印链接列表的递归方法

[英]Recursive method that prints a linked list in reverse order

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. 我已经创建了一个名为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 1,2,3,4

You'd call print on the node with 1 in it. 您将在节点上调用print,其中包含1。 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. 2节点还具有下一个节点,因此它遵循节点3.节点3仍然具有下一个节点,因此在打印之前它将延迟到节点4。 Node 4 is willing to print itself since it has no next node. 节点4愿意打印自己,因为它没有下一个节点。 Then it returns to where node 3 left off. 然后它返回到节点3停止的位置。 Now node 3 can print and go back to where node 2 left off. 现在节点3可以打印并返回到节点2停止的位置。 It prints and goes to where node 1 left off. 它打印并转到节点1停止的位置。 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. 我同意100%的上述答案,对于我的实现,如果没有帮助类,我无法使用它。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM