剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 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().
*/
int* reversePrint(struct ListNode* head, int* returnSize)
{
struct ListNode* p;
int *a;
int j = 0;
p = head;
while(p)
{
p = p->next;
j++;
}
a = (int*)malloc(sizeof(int)*j);
*returnSize = j;
p = head;
j = j-1;
while(j>=0 && p != NULL)
{
a[j] = p->val;
p = p->next;
j--;
}
return a;
}