输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//从尾到头就是压栈出栈
Stack<ListNode> sta = new Stack<ListNode>();//栈的初始化
ListNode temp = head;
while(temp != null){
sta.push(temp);//进栈函数
temp = temp.next;
}
int n = sta.size();//栈的长度
int arr[] = new int[n];
for(int i = 0; i < n; i ++){
arr[i] = sta.pop().val;//出栈函数,出来的是链表,要的是链表里的值
}
return arr;
}
}
方法2:不使用栈,遍历链表两次,把数组从后往前赋值
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode temp = head;
int size = 0;//记录链表长度
while(temp != null){
size ++;
temp = temp.next;
}
temp = head;//还原指针
int arr[] = new int[size];
for(int i = arr.length -1; i >= 0; i --){
arr[i] = temp.val;
temp = temp.next;
}
return arr;
}
}