题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值,链表节点定义如下:
public class ListNode { int val; ListNode* next; ListNode(int x) { this.val = x; this.next = null; } }
解法:
- 迭代——使用栈保存每个结点的数据,遍历结束后逐个输出栈值;
- 递归——递归输出当前结点后面的结点
// 解法一
public int[] reversePrint(ListNode head) {
if (head == null)
return new int[]{};
ListNode node = head;
Stack<Integer> stack = new Stack<>();
while(node != null) {
stack.push(node.val);
node = node.next;
}
int[] res = new int[stack.size()];
int idx = 0;
while(!stack.isEmpty()) {
res[idx] = stack.pop();
idx++;
}
return res;
}
// 解法二
public void printLinkedList(ListNode head) {
if (head == null)
return;
printLinkedList(head.next);
System.out.println(head.val);
}