2
头图

Print linked list from end to beginning

Title description

Enter a linked list and return an ArrayList in the order from the end to the beginning of the linked list.

Title link: Print the linked list from end to

Code

import java.util.ArrayList;

/**
 * 标题:
 * 题目描述
 * 
 * <p>
 * 题目链接
 * 
 */
public class Jz03 {

    /**
     * 非递归
     *
     * @param listNode
     * @return
     */
    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> res = new ArrayList<>();
        for (; listNode != null; listNode = listNode.next) {
            res.add(0, listNode.val);
        }
        return res;
    }

    /**
     * 递归
     *
     * @param listNode
     * @return
     */
    public static ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (listNode != null) {
            res.addAll(printListFromTailToHead1(listNode.next));
            res.add(listNode.val);
        }
        return res;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(67);
        ListNode node1 = new ListNode(0);
        ListNode node2 = new ListNode(24);
        ListNode node3 = new ListNode(58);
        node.next = node1;
        node1.next = node2;
        node2.next = node3;

        // 非递归
        System.out.println("非递归~~~");
        ArrayList<Integer> res = printListFromTailToHead(node);
        for (int val : res) {
            System.out.println(val);
        }

        // 递归
        System.out.println("递归~~~");
        ArrayList<Integer> res1 = printListFromTailToHead1(node);
        for (int val : res1) {
            System.out.println(val);
        }
    }
}
[Daily Message] If you are in the right direction, you are not afraid of the long way. Persistence is not only a quality, but also a belief.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!