从尾到头,不是从头到尾,这里主要问题是:要求返回一个数组,一是长度不好确定,只有遍历完这个链表,才能确定其长度。
代码:
/**
* 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 len = 0;
int *result = malloc(sizeof(int) * 10000);
while (head != NULL) {
result[len++] = head->val;
if (head->next == NULL) break;
head = head->next;
}
*returnSize = len;
// 翻转数组
for (int i = 0; i < len / 2; i++) {
int tmp = result[i];
result[i] = result[len - 1 - i];
result[len - 1 - i] = tmp;
}
return result;
}
这里先从头到尾遍历链表,像数据记录再数组中,并记录其长度,再将这个数组反转,就得到了从尾到头的顺序。
结果: