题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList

方法一:

翻转链表,然后重新遍历放入到数组中;

  1. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
  2. ListNode pre = null, now = listNode, next = listNode;
  3. //1->2->3->4
  4. while (now != null) {
  5. next = now.next;
  6. now.next = pre;
  7. pre = now;
  8. now = next;
  9. }
  10. ArrayList<Integer> arrayList = new ArrayList<>();
  11. while (pre != null) {
  12. arrayList.add(pre.val);
  13. pre = pre.next;
  14. }
  15. return arrayList;
  16. }

方法二:

依次遍历放入栈中,然后遍历栈

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Stack;
  4. import java.util.ArrayList;
  5. public class Solution {
  6. //
  7. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
  8. Stack<Integer> stack = new Stack<>();
  9. while (listNode != null) {
  10. stack.push(listNode.val);
  11. listNode = listNode.next;
  12. }
  13. ArrayList arr = new ArrayList();
  14. while (!stack.isEmpty()) {
  15. arr.add(stack.pop());
  16. }
  17. return arr;
  18. }
  19. }

方法三:

递归