输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:输入:head = [1,3,2] 输出:[2,3,1]
思路分析:
- 计算数据个数,开辟空间。
- 再对数组内每一个元素,按顺序进行赋值。
- 最后返回数组首元素的地址
int* reversePrint(struct ListNode* head, int* returnSize){
struct ListNode* newnode=head;
int count=0;
while(head)
{
head=head->next;
count++;//计算有多少数据
}
*returnSize=count;
int* array=(int*)calloc(count,sizeof(int));
for(int i=count-1;i>=0;i--)//在数组中存放数据
{
array[i]=newnode->val;
newnode=newnode->next;
}
return array;
}
复杂度分析:
- 时间复杂度:O(N)
- 空间复杂度:O(N)