剑指 Offer 06. 从尾到头打印链表 #
题目 #
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
思路 #
代码 #
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public void helper(ListNode head, List<Integer> resultList) {
if (head == null) return;
else if (head.next == null) resultList.add(head.val);
else {
helper(head.next, resultList);
resultList.add(head.val);
}
}
public int[] reversePrint(ListNode head) {
List<Integer> resultList = new ArrayList<>();
helper(head, resultList);
int[] result = new int[resultList.size()];
for (int i=0; i<resultList.size(); i++) result[i] = resultList.get(i);
return result;
}
}