力扣每日一题——剑指 Offer 06. 从尾到头打印链表
题目描述
代码注释
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
//先遍历一遍链表获得长度
struct ListNode* p;
p = head;
int count=0;
while(p!=NULL){
count++;
p=p->next;
}
//开辟数组空间存放链表数据
int * res = (int *)malloc(sizeof(int) * count);
//将链表数据倒着放入数组中
p=head;
for(int i = count-1;i>=0;i--){
res[i]=p->val;
p=p->next;
}
*returnSize=count;
return res;
}
提交结果如下:
反思心得
遇到报错如下:
因为我原来的函数是直接int res[count-1]
定义的数组,返回的是指针地址指向函数内的局部变量数组,在函数退出时,数组的存储空间会被销毁,所以访问该地址就会出现这个错误。
修改方法一般有3种:
1)用malloc给返回的指针分配空间(就是我正确代码中那样)
2)用static修饰变量
3)使用全局变量