牛客网刷题(JAVA) 9:从尾到头打印链表

难度系数 ⭐⭐【难在不会使用this】

时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

题目内容 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

思路 遍历链表,若当前节点非空,观察下一个节点,并保存当前信息(用于递归)。

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    ArrayList<Integer> result = new ArrayList<>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if (listNode != null) {
            this.printListFromTailToHead(listNode.next);
            result.add(listNode.val);
        }
        return result;
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/105422949