剑指Offer(三)从尾到头打印链表

来源:互联网 发布:淘宝采集软件收费吗 编辑:程序博客网 时间:2024/05/17 19:16

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

/***    public class ListNode {*        int val;*        ListNode next = null;**        ListNode(int val) {*            this.val = val;*        }*    }**/import java.util.ArrayList;import java.util.Stack;public class Solution {    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {        Stack<Integer> stack = new Stack<Integer>();//用栈存储节点元素        ListNode p = listNode;        while(p != null){            stack.add(p.val);            p = p.next;        }        ArrayList<Integer> array = new ArrayList<Integer>();        while(stack.size() != 0){            array.add(stack.pop());//利用栈后进先出的特性倒序存入输入的值        }        return array;    }}
原创粉丝点击