输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:0 <= 链表长度 <= 10000
leetcode:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
解题思路
从尾到头打印链表,即LIFO,使用栈,最后数组输出,第一次考虑选择ArrayList转为Array时出错,不能转换成功,网上有通过java.util.stream中的array.stream().mapToInt(Integer::intValue).toArray();返回,但是还是出错,未能找到解决方案,菜鸡不才,只能通过构造int[]来达到题目要求。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head){
if(head == null){
int[] array = new int[0];
return array;
}
Stack<Integer> stack = new Stack<>();
while(head != null){
stack.add(head.val);
head = head.next;
}
int i = 0;
int[] array = new int[stack.size()];
while(!stack.isEmpty()){
array[i++] = stack.pop();
}
return array;
}
}