题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList
方法一:
翻转链表,然后重新遍历放入到数组中;
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode pre = null, now = listNode, next = listNode;
//1->2->3->4
while (now != null) {
next = now.next;
now.next = pre;
pre = now;
now = next;
}
ArrayList<Integer> arrayList = new ArrayList<>();
while (pre != null) {
arrayList.add(pre.val);
pre = pre.next;
}
return arrayList;
}
方法二:
依次遍历放入栈中,然后遍历栈
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
//
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>();
while (listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList arr = new ArrayList();
while (!stack.isEmpty()) {
arr.add(stack.pop());
}
return arr;
}
}
方法三:
递归