从尾到头打印链表
题目:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
方法一:栈。遍历链表将节点值压栈,然后弹出到数组。
class Solution {
public int[] reversePrint(ListNode head) {
Stack st = new Stack<>();
while(head != null){
st.push(head.val);
head = head.next;
}
int size = st.size();
int[] ans = new int[size];
for(int i = 0; i < size; i++){
ans[i] = st.pop();
}
return ans;
}
}
方法二:数组。第一次遍历链表获取链表长度,第二次遍历链表将节点值从后往前填充进数组。
class Solution {
public int[] reversePrint(ListNode head) {
ListNode cur = head;
int size = 0;
while(cur != null){
size++;
cur = cur.next;
}
int[] ans = new int[size];
cur = head;
for(int i = size - 1; i >= 0; i--){
ans[i] = cur.val;
cur = cur.next;
}
return ans;
}
}
其他方法:反转链表+遍历



