剑指 Offer 06. 从尾到头打印链表-easy
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
解法:遍历链表,放入list中,从后往前循环list放入数组中。
public int[] reversePrint(ListNode head) {
//特殊判断
if(head == null) return new int[0];
List<Integer> sb = new ArrayList<>();
//循环遍历链表放入list中
while (head != null){
sb.add(head.val);
head = head.next;
}
int[] result = new int[sb.size()];
int n = 0;
for (int i = sb.size() - 1; i >= 0; i--) {
result[n] = sb.get(i);
n++;
}
return result;
}
以上~