题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
1
2
2
限制:
0 <= 链表长度 <= 10000
题解
java
public int[] reversePrint(ListNode head) {
int count = 0;
ListNode cursor = head;
// 获取链表长度
while (cursor != null) {
cursor = cursor.next;
count++;
}
int[] result = new int[count];
// 重置指针
cursor = head;
// 倒叙设置数组值
while (cursor != null) {
result[--count] = cursor.val;
cursor = cursor.next;
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20