剑指06 从尾到头打印链表

  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. Stack<Integer> stack = new Stack<Integer>();
  12. ListNode p = head;
  13. while (head != null) {
  14. stack.push(head.val);
  15. head = head.next;
  16. }
  17. int[] ans = new int[stack.size()];
  18. for (int i = 0; i < ans.length; i++) {
  19. ans[i] = stack.peek();
  20. stack.pop();
  21. }
  22. return ans;
  23. }
  24. }