题目要求:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
例题:
输入:head = [1,3,2]
输出:[2,3,1]
题目分析:
第一步:创建栈,将链表的节点存入栈中;
第二步:获取栈的长度len,创建数组大小为len;
第三步:将栈中的节点弹出,并存入数组;
第四步:返回数组;
代码实现:
class test {
public int[] EndtoHeadListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int len = stack.size();
int[] print = new int[len];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}