从尾到头打印链表

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

  1. 输入:head = [1,3,2]
  2. 输出:[2,3,1]

两种解法:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public int[] reversePrint(ListNode head) {
  11. /**
  12. *解法二:Stack
  13. */
  14. Stack<Integer> stack = new Stack<Integer>();
  15. int size = 0; //数组长度
  16. while(head != null){
  17. stack.push(head.val);
  18. head = head.next;
  19. size++;
  20. }
  21. int[] ans = new int[size];
  22. for(int i = 0; i < size; i++){
  23. ans[i] = stack.pop();
  24. }
  25. return ans;
  26. /**
  27. *解法一
  28. */
  29. /**
  30. ListNode temp = head;
  31. int length = 0;
  32. while(head != null){
  33. length++;
  34. head = head.next;
  35. }
  36. int[] ans = new int[length];
  37. for (int i = length-1; i >= 0; i--){
  38. ans[i] = temp.val;
  39. temp = temp.next;
  40. }
  41. return ans;
  42. **/
  43. }
  44. }