题目

牛客网

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

解题思路

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
LinkedList<Integer> stack = new LinkedList<>();

while (listNode != null) {
    stack.addLast(listNode.val);
    listNode = listNode.next;
}

ArrayList<Integer> res = new ArrayList<>();

while (!stack.isEmpty()) {
    res.add(stack.pollLast());
}

return res;
}
  1. 递归:当链表过长时,会导致栈溢出
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> res = new ArrayList<>();

    print(res,listNode);

    return res;
}

private void print(ArrayList<Integer> res, ListNode listNode) {
    if (listNode == null) return;

    print(res, listNode.next);

    res.add(listNode.val);
}

results matching ""

    No results matching ""