题解 | #从尾到头打印链表# 栈 / 递归

从尾到头打印链表

http://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035

方法一:栈

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Deque<Integer> stack = new ArrayDeque<>();
        ListNode cur = listNode;
        while (cur != null) {
            stack.push(cur.val);
            cur = cur.next;
        }
        return new ArrayList<Integer>(stack);
    }
}

方法二:递归

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    ArrayList<Integer> list = new ArrayList<Integer>();
    
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        recur(listNode);
        return list;
    }
    
    private void recur(ListNode node) {
        if (node == null) {
            return;
        }
        recur(node.next);
        list.add(node.val);
    }
}
全部评论

相关推荐

10-01 09:50
门头沟学院 Java
肖先生~:这个人真的很好,点赞
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务