题目:
思路:
- 两次遍历链表,第一次得到链表的 length ;
- 定义一个返回数组,长度为 链表的 length ;
- 为数组反向赋值,赋值完成,也就将链表反向存储到数组中。
实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
int count = 0;
ListNode temp = head;
while (temp != null) {
count++;
temp = temp.next;
}
int[] res = new int[count];
for (int i = count - 1; i >= 0; i--) {
res[i] = head.val;
head = head.next;
}
return res;
}
}