输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
/*使用迭代*/
struct ListNode* reverseList(struct ListNode* head, int* returnSize){
struct ListNode* prr=NULL;
struct ListNode* crr=head;
while(crr){
(*returnSize)++;
struct ListNode* next=crr->next;
crr->next=prr;
prr=crr;
crr=next;
}
return prr;
}
int* reversePrint(struct ListNode* head, int* returnSize){
int i=0;
*returnSize=0;
int* ans=(int*)malloc(10000*sizeof(int));
head=reverseList(head,returnSize);
//避免空间浪费,分配returnSize个大小的空间
ans=(int*)malloc(sizeof(int)*(*returnSize));
//此处不使用malloc则会导致最后是空指针,因为退出该函数时,局部变量数组也被销毁了
while(head!=NULL){
ans[i++]=head->val;
head=head->next;
}
return ans;
}
此处自己的做法是先反转链表,再把链表中的数据存到数组当中。该题中有两个易错点:
1.一开始自己的思路如下。问题在于此处的ans为局部变量数组,此处的p为局部指针,因此当退出了函数后,局部变量数组也会被销毁,因此会报空指针的错误。
int* reversePrint(struct ListNode* head, int* returnSize){
int i=0;
*returnSize=0;
int ans[10001];
int *p;
head=reverseList(head,returnSize);
ans=(int*)malloc(sizeof(int)*(*returnSize));
while(head!=NULL){
ans[i++]=head->val;
head=head->next;
}
p=ans;
return p;
}
2.自己做的时候没有在意returnSize,实际上是要计数的。