输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:输入:head = [1,3,2]输出:[2,3,1]限制:0 <= 链表长度 <= 10000
利用栈思想
遍历链表,并将每个元素入栈,然后再反过来出栈进入数组即可。
/*** 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){*returnSize = 0;if (head == NULL) return NULL;int stack[10001];int top = -1;while (head) {stack[++top] = head->val;head = head->next;}int *res = (int *)malloc(sizeof(int) *(top+1));while(top != -1) {res[(*returnSize)++] = stack[top--];}return res;}
