Java语言解题简单实现(从尾到头打印链表)

从尾到头打印链表

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

JAVA实现
先保存到一个中间List中,然后倒序获取元素,存入新的List,返回结果。

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ListNode currentNode = listNode;
        ArrayList<Integer> tempList = new ArrayList<Integer>();

        while(currentNode != null){
            tempList.add(currentNode.val);
            currentNode = currentNode.next;
        }
        // 翻转
        ArrayList<Integer> endList = new ArrayList<Integer>();
        for(int i=tempList.size()-1; i>=0; i--){
            endList.add(tempList.get(i));
        }
        return endList;
    }
}
全部评论
""" ArrayList<integer> arrayList = new ArrayList(); Stack<integer> stack = new Stack<>(); LstNode tmp = lstNode; while (tmp != null) { stack.push(tmp.val); tmp = tmp.next; } final int size = stack.size(); for (int i = 0; i < size; i++) { arrayList.add(stack.pop()); } """</integer></integer>
点赞 回复 分享
发布于 2019-11-22 21:57
ArrayList<integer> arrayList = new ArrayList(); Stack<integer> stack = new Stack<>(); LstNode tmp = lstNode; while (tmp != null) { stack.push(tmp.val); tmp = tmp.next; } final int size = stack.size(); for (int i = 0; i < size; i++) { arrayList.add(stack.pop()); }</integer></integer>
点赞 回复 分享
发布于 2019-11-22 21:57
总感觉这种方式不优雅,用这个还不如用栈来存,不用反转
点赞 回复 分享
发布于 2019-11-22 21:56
考虑最后一个结点没有next,你的这个逻辑最后一个没有下一个节点的这个结点的val丢失了吧
点赞 回复 分享
发布于 2019-11-05 21:34

相关推荐

AAA不喝拿铁:西电本硕学历没问题,但是项目名字首先得改虽然一眼能看出来是点评但是不能演都不演就直接给面试官端上去。技术点全是redis显得这像redis的课程实验,也要改。我根据真实面经整理得到的最全(高/中/低频)面试题,需要的牛u可以订阅一手我的专栏,祝好运
点赞 评论 收藏
分享
评论
8
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务