输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
重点:
局部变量在函数结束时会自动删除,不能作为返回值,需要使用malloc 或者 static 才能在函数返回时不被删除
说到逆序 首先想到的就是递归,但是苦于作为函数的局部变量在函数结束时会自动删除,没有想到解决办法
看了别人的答案发现可以使用malloc 或者 static 解决
//
int* reversePrint(struct ListNode* head, int* returnSize){
if( head == NULL )
{
*returnSize = 0;
return malloc(10000*sizeof(int));
}
int * res = reversePrint(head->next,returnSize);
res[ (*returnSize)++] = head->val;
return res;
}
基本步骤:
- 1、动态建立数组 用于作为返回值;
- 2、读取到数组
- 3、数组逆序
/**
* 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* cur = head;
int arr[10000];
int *arr2 = (int *)malloc(10000*sizeof(int));
int i = 0;
while(cur != NULL)
{
arr[i] = cur->val;
cur = cur -> next;
i++;
}
*returnSize = i;
for(int j =i-1 ,k = 0;j >= 0 ; j--,k++)
{
arr2[k] = arr[j];
}
return arr2;
}
int* reversePrint(struct ListNode* head, int* returnSize){
struct ListNode* cur = head;
int *arr = (int *)malloc(10000*sizeof(int));
int i = 0;
while(cur != NULL)
{
arr[i] = cur->val;
cur = cur -> next;
i++;
}
*returnSize = i;
for(int j = 0 ; j< (*returnSize )/2;j++)
{
arr[j] = ( arr[i-1-j] + arr[j] ) - (arr[i-1-j] = arr[j]) ;
}
return arr;
}
------后面是一些废话
一开始调整数组交换方式发现时间消耗差的有点多,后来连续提交同一个代码才发现,每次运行时间会有差别,这就有点不太靠谱了
int* reversePrint(struct ListNode* head, int* returnSize){
struct ListNode* cur = head;
int *arr = (int *)malloc(10000*sizeof(int));
int i = 0;
while(cur != NULL)
{
arr[i] = cur->val;
cur = cur -> next;
i++;
}
*returnSize = i;
for(int j = 0 ; j< (*returnSize )/2;j++)
{
// arr[j] = ( arr[i-1-j] + arr[j] ) - (arr[i-1-j] = arr[j]) ;
int temp;
temp = arr[j];
arr[j] = arr[i-1-j];
arr[i-1-j] = temp;
}
return arr;
}
修改了交换数组的方式 发现
连续两次提交运行时间不同,这就有点难受了。