方法1:利用ArrayList
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] printListReversingly(ListNode head) {
ArrayList<Integer> al = new ArrayList<>();
ListNode l = head;
int size = 0;
while(l!= null) {
al.add(0,l.val);
size ++;
l = l.next;
}
int[] res = new int[size];
for(int i = 0; i < size; i++) {
res[i] = al.get(i);
}
return res;
}
}
比方法2快
方法2:反转链表
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] printListReversingly(ListNode head) {
if(head == null) return new int[]{}; //额
if(head.next == null) return new int[] {head.val};
ListNode pre = null,node = head, next = null;
int cnt = 0;
while(node != null) {
next = node.next;
node.next = pre;
pre = node;
node = next;
cnt ++;
}
head = pre;
int[] ans = new int[cnt];
for(int i = 0; i < cnt; i++,head = head.next)
ans[i] = head.val;
return ans;
}
}