[wrong code]
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
if(head==null){
return new int[0];
}
int[] arr=new int[0];
rev(head, arr, 0);
return arr;
}
void rev(ListNode head, int[] arr, int lv){
if(head.next==null){
arr = new int[lv+1];
arr[lv] = head.val;
return;
}
lv++;
rev(head.next, arr, lv);
lv--;
arr[lv] = head.val;
}
}
[wrong code]
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
if(head==null){
return new int[0];
}
int n=1;
while(head.next!=null){
n++;
head=head.next;
}
int[] arr=new int[n];
rev(head, arr, n-1);
return arr;
}
void rev(ListNode head, int[] arr, int lv){
if(head==null){
return;
}
if(lv==0){
arr[lv] = head.val;
return;
}
//lv--;
rev(head.next, arr, lv-1);
//lv++;
arr[lv] = head.val;
}
}```