1. 反转链表
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
if (listNode == null) return ret;
listNode = reverseLinkedList(listNode);
while (listNode != null) {
ret.add(listNode.val);
listNode = listNode.next;
}
return ret;
}
private ListNode reverseLinkedList(ListNode node) {
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
ListNode next = null;
while (node != null) {
next = node.next;
node.next = dummyHead.next;
dummyHead.next = node;
node = next;
}
return dummyHead.next;
}
}
2. 反转集合
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
if (listNode == null) return ret;
while (listNode != null) {
ret.add(listNode.val);
listNode = listNode.next;
}
Collections.reverse(ret);
return ret;
}
}
3. 递归
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
if (listNode == null) return ret;
recursion(ret, listNode);
return ret;
}
private void recursion(ArrayList<Integer> ret, ListNode listNode) {
if (listNode.next != null)
recursion(ret, listNode.next);
ret.add(listNode.val);
}
}