题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路:本来想用StringBuilder的但是一看要返回int数组就放弃了。
因为无法确定到底有多少节点,最后直接先建立一个10001的int数组
代码
package test01;
import java.util.Arrays;
public class Q6 {
public static void main(String[] args) {
// head = [1,3,2]
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(3);
ListNode node3 = new ListNode(2);
node1.next = node2;
node2.next = node3;
node3.next = null;
System.out.println(Arrays.toString(reversePrint(node1)));
}
public static int[] reversePrint(ListNode head) {
// System.out.println(head.val);
// System.out.println(head == null);
if(head == null) {
return new int[0];
}
int[] arr = new int[10001];
arr[10000] = head.val;
int index = 9999;
ListNode next = head.next;
while(next != null) {
arr[index] = next.val;
next = next.next;
index --;
}
int[] ans = Arrays.copyOfRange(arr, index+1, 10001);
return ans;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
不过,我看很多解析都是用的栈,当初我也想到类似的但是那样要遍历两次数组,我只想遍历一遍,只能牺牲空间了。