剑指offer系列牛客——倒序打印单向链表值

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

单向链表的遍历是从头至尾,要求从尾至头打印,这种先进后出的模式很像栈,因此构建一个临时栈存储链表的值,再从栈中弹出依次存储即可。

代码如下:

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ListNode node= listNode;
        Stack<Integer> store= new Stack();
        ArrayList<Integer> res= new ArrayList<>();
        while(node!= null){
            store.push(node.val);
            node= node.next;
        }
        while(!store.isEmpty()){
            res.add(store.pop());
        }
        return res;
    }
}

一开始新建栈对象时语句为Stack store= new Stack()结果报错,不能将object存储至Integer中,这种设定存储类型的细节还是要注意

tips:如何使用栈实现先进先存的案例呢?(注意先进先存与先进先出不一样,栈是肯定要先进后出的,但可以再不弹出元素的情况下实现先遍历底层的操作)

for(Integer x: s) {
            System.out.print(x+" ");
 }

猜你喜欢

转载自blog.csdn.net/better_girl/article/details/84650698