题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
/**
* 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){
if(NULL == head){
* returnSize = 0;
return NULL;
}
struct ListNode *p = head;
int count = 0;
int i = 0;
int* temp = (int*)malloc(sizeof(int) * 10000);
int* res = (int*)malloc(sizeof(int) * 10000);
while(NULL != p->next){
temp[count] = p->val;
count++;
p = p->next;
}
temp[count] = p->val;
count++;
*returnSize = count;
for(i = 0;i < count;i++){
res[i] = temp[count - 1 - i];
}
return res;
}
运行结果: