1. 从尾到头打印链表
输入一个链表,按链表从尾到头的顺序返回一个 List
2. 解法
2.1 辅助栈
借助栈先入后出的特性,可以很轻松地实现
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>();
while (listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> list = new ArrayList<>();
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
2.2 Collections 工具类
JDK 中提供了操作集合类的工具类 Collections
,其支持的功能就包括了逆转链表。从 Collections
的实现看,其逆转功能在底层其实也就是链表元素位置的交换
public ArrayList<Integer> PrintListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<>();
while (listNode != null) {
list.add(listNode.val);
listNode = listNode.next;
}
// Collections 的reverse方法,直接将list反转
Collections.reverse(list);
return list;
}