题目

image.png

代码

  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. if(head == null) return new int[0];
  12. Stack<Integer> stack = new Stack<>();
  13. List<Integer> l = new ArrayList<>();
  14. ListNode cur = head;
  15. while(cur != null ) {
  16. stack.push(cur.val);
  17. cur = cur.next;
  18. }
  19. while(!stack.isEmpty() ) {
  20. l.add(stack.pop());
  21. }
  22. return l.stream().mapToInt(Integer::intValue).toArray();
  23. }
  24. }
  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<>();
  12. while (head != null) {
  13. stack.push(head.val);
  14. head = head.next;
  15. }
  16. int[] res = new int[stack.size()];
  17. int i = 0;
  18. while (!stack.isEmpty()) {
  19. res[i ++] = stack.pop();
  20. }
  21. return res;
  22. }
  23. }