1. 程式人生 > >3:從尾到頭列印連結串列

3:從尾到頭列印連結串列

題目描述

解題思路

藉助棧

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; } }