【问题标题】:What is actually happening in the code here这里的代码中实际发生了什么
【发布时间】:2020-05-26 15:16:11
【问题描述】:

void 反向(节点头){ if(head==null) 返回;

    reverse(head.next);
    System.out.print(head.data+" ");
}

【问题讨论】:

  • 这是一种递归方法,旨在反向打印我认为是 LinkedList 的内容
  • 你自己追踪一下,你会看到
  • 糟糕的标题。重写以总结您的具体技术问题。

标签: java linked-list program-flow


【解决方案1】:

它从末尾打印链表的内容。

考虑这个简单的列表: 1 -> 2 -> 3

现在让我们“分解”调用:

reverse(1) :
    reverse(2) :
        reverse(3) :
        print(3)
    print(2)
print(1)

奇迹发生是因为 println 在递归调用之后被调用!尝试把它放在前面会按正常顺序打印列表。

【讨论】:

    【解决方案2】:

    本质上,您正在反转链表的跟踪过程。

    void reverse(Node head) {
            if(head==null) //if head points to nothing
                 return;
            reverse(head.next); #if head points to something, move one position in reverse, because of the recursion, the function is called again before printing anything
            System.out.print(head.data+" "); #print the data stored in the nodes, reversed
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2011-03-31
      相关资源
      最近更新 更多