递归实现
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0; i < res.length; i++)
res[i] = tmp.get(i);
return res;
}
void recur(ListNode head) {
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
}
List集合
class Solution {
public int[] reversePrint(ListNode head) {
List<Integer> res = new ArrayList<>();
ListNode cur = head;
while(cur != null){
res.add(cur.val);
cur = cur.next;
}
int[] ans = new int[res.size()];
int size = res.size() - 1;
for(int i = 0; i < res.size(); i++){
ans[i] = res.get(size);
size--;
}
return ans;
}
}
剑指 Offer 06. 从尾到头打印链表
最新推荐文章于 2024-11-05 21:58:11 发布