题解
迭代
先求出链表的长度,最后反着添加元素即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode node = head;
int count = 0;
while(node != null){
node = node.next;
count ++;
}
int[] res = new int[count];
for(int i = count - 1; i >= 0; -- i){
res[i] = head.val;
head = head.next;
}
return res;
}
}
回溯
直接利用回溯算法直接就是从后面添加
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public int[] reversePrint(ListNode head) {
backTracking(head);
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); ++ i){
res[i] = list.get(i);
}
return res;
}
void backTracking(ListNode head){
if(head == null) return;
backTracking(head.next);
list.add(head.val);
}
}