题目描述
分析
题目要求从头到尾反向输出每个节点的值(并用数组返回),看到官方的题解是用栈来解决的(栈先进后出的特点),但自己目前还没有接触到,所以先用一个时间复杂度和空间复杂度复杂的方法吧,之后学到了再补充。
- 第一步,先遍历链表求出链表长度len
- 第二步,new一个len大小的数组
- 第三步,将结点的每一个值都存到数组中(注意,从后往前存)
- 返回数组即可
AC代码
class Solution {
public int[] reversePrint(ListNode head) {
ListNode cur=head;
int len=0;
while(cur!=null)
{
len++;
cur=cur.next;
}
cur=head;
int[] arr=new int[len];
while(cur!=null)
{
arr[len-1]=cur.val;
len--;
cur=cur.next;
}
return arr;
}
}