题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
题目链接:https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
解题思路
借助栈
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<Integer> result = new ArrayList<>();
while (!stack.isEmpty()) {
result.add(stack.pop());
}
return result;
}
}
使用递归的方式
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> result = new ArrayList<>();
if (listNode == null) return result;
result.addAll(printListFromTailToHead(listNode.next));
result.add(listNode.val);
return result;
}
}
借助链表原地反转的思想
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> result = new ArrayList<>();
if (listNode == null) return result;
if (listNode.next == null) {
result.add(listNode.val);
return result;
}
ListNode pre = null;
ListNode next = null;
while (listNode != null) {
next = listNode.next;
listNode.next = pre;
pre = listNode;
listNode = next;
}
while (pre != null) {
result.add(pre.val);
pre = pre.next;
}
return result;
}
}