题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路
将这个链表逆置,然后再直接存到一个ArrayList。
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<>();
//逆置单链表
ListNode pre = null;
ListNode next = null;
while (listNode != null) {
next = listNode.next;
listNode.next = pre;
pre = listNode;
listNode = next;
}
while (pre != null) {
list.add(pre.val);
pre = pre.next;
}
return list;
}