题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
网上还有其他方法,我这里使用的是改变链表本身数据结构,将链表元素的next倒置:
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> lList = new ArrayList<Integer>();
ListNode pre = null;
ListNode cur = listNode;
ListNode head = null;
while (cur != null) {
ListNode nextNode = cur.next;
if (nextNode == null) {
head = cur;
}
cur.next = pre;
pre = cur;
cur = nextNode;
}
ListNode node = head;
while(node!=null){
lList.add(node.val);
node = node.next;
}
return lList;
}
}