题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值,链表节点定义如下
class ListNode{
int key;
ListNode next;
}
思路:通过递归的方式实现,但注意层级不能太深,否则会导致函数调用栈溢出。
解决方案:
public class Question6 {
public static void PrintListReversingly_Recursively(ListNode head){
if (head != null){
if (head.next != null){
PrintListReversingly_Recursively(head.next);
}
System.out.println(head.key);
}
}
static class ListNode{
int key;
ListNode next;
}
public static void main(String[] args) {
ListNode head = new ListNode();
ListNode second = new ListNode();
head.key = 0;
second.key = 1;
head.next = second;
PrintListReversingly_Recursively(head);
}
}









网友评论