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

从尾到头打印链表

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);
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:20
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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