06从尾到头打印链表
题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入输出
输入:head = [1,3,2]
输出:[2,3,1]
解决方案
- 使用栈来解决
输出的放入栈中,然后反向输出
public static int[] reversePrint(ListNode head) {
Stack<Integer> st = new Stack<Integer>();
while(head!=null){
st.push(head.val);
head = head.next;
}
int result[] = new int[st.size()];
int index=0;
while(!st.empty()){
result[index++]=st.pop();
}
return result;
}
- 扫描法
先扫描一遍链表获取长度,创建数组,数组指针从后往前填
public static int[] reversePrint(ListNode head) {
ListNode node = head;
int count = 0;
while (node != null) {
++count;
node = node.next;
}
int[] nums = new int[count];
node = head;
for (int i = count - 1; i >= 0; --i) {
nums[i] = node.val;
node = node.next;
}
return nums;
}