前言
题目描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
一、示例
二、代码
代码如下(示例):
/**
* 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){
int num = 0;
struct ListNode* p = (struct ListNode*)malloc(1 * sizeof(struct ListNode));
struct ListNode* q = (struct ListNode*)malloc(1 * sizeof(struct ListNode));
p = head;
q = head;
while(p) {
++num;
p = p->next;
}
*returnSize = num;
int* new_array = (int*)malloc( sizeof(int) * (num + 1) );
for(; num > 0; --num) {
new_array[num-1] = q->val;
q = q->next;
}
return new_array;
}