Lcof06

Lcof 06.从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

​ 输入:head = [1,3,2]
​ 输出:[2,3,1]

因为栈具有先进后出的特点,所以在遍历链表时将值push到栈中,pop的顺序即为逆序。

class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> tmp = new Stack<Integer>();
ListNode temp = head;
while (temp != null) {
tmp.push(temp.val);
temp = temp.next;
}
// 要记录size,因为pop后size()会改变
int size = tmp.size();
int[] ret = new int[size];
for (int i = 0; i < size; i++) {
ret[i] = tmp.pop();
}
return ret;
}
}
Author: Jiayi Yang
Link: https://jiayiy.github.io/2020/05/31/Lcof06/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.