題目:
思路:
- 兩次遍歷鏈表,第一次得到鏈表的 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;
}
}