剑指Offer第三题:从头到尾打印链表

从尾到头打印链表

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解答:
1.栈的方法
public ArrayList<integer> printListFromTailToHead(ListNode listNode){</integer>

    Stack<Integer> stack=new Stack<Integer>();
    ArrayList<Integer> arrayList=new ArrayList<>();
    if(listNode==null){
        return arrayList;
    }
    while(listNode!=null){
        stack.push(listNode.val);
        listNode=listNode.next;
    }
    while (!stack.isEmpty()){
        arrayList.add(stack.pop());
    }
    return arrayList;

}

2.递归方法
public class Solution {

ArrayList<Integer> arrayList=new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
   if (listNode!=null){
        printListFromTailToHead(listNode.next);
        arrayList.add(listNode.val);
    }
    return arrayList;
}

}

全部评论

相关推荐

头像
01-29 18:11
海南大学 Java
奔跑的suechil...:单从项目看这个简历不怕被问穿吗 带微服务的项目需要相当多的项目理解和经验诶
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

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