题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
两次遍历,一次统计长度,一次逆序输出。
int* printListFromTailToHead(struct ListNode* listNode, int* returnSize ) { int *res; struct ListNode* tmp = listNode; int n = 0; while (tmp) { n++; tmp = tmp->next; } printf("%i", n); *returnSize = n; res = (int*)malloc(sizeof(int) * n); for (int i = n - 1; i >= 0; i--) { res[i] = listNode->val; // printf("%i", listNode->val); listNode = listNode->next; } return res; // write code here }