输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

  1. 示例:
  2. 输入:head = [1,3,2]
  3. 输出:[2,3,1]
  4. 限制:
  5. 0 <= 链表长度 <= 10000

利用栈思想

遍历链表,并将每个元素入栈,然后再反过来出栈进入数组即可。

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * struct ListNode *next;
  6. * };
  7. */
  8. /**
  9. * Note: The returned array must be malloced, assume caller calls free().
  10. */
  11. int* reversePrint(struct ListNode* head, int* returnSize){
  12. *returnSize = 0;
  13. if (head == NULL) return NULL;
  14. int stack[10001];
  15. int top = -1;
  16. while (head) {
  17. stack[++top] = head->val;
  18. head = head->next;
  19. }
  20. int *res = (int *)malloc(sizeof(int) *(top+1));
  21. while(top != -1) {
  22. res[(*returnSize)++] = stack[top--];
  23. }
  24. return res;
  25. }