码迷,mamicode.com
首页 > 其他好文 > 详细

<剑指offer> 第3题

时间:2019-06-10 22:28:37      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:port   null   color   import   off   print   入栈   arraylist   new   

题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值

将链表从头到尾压入栈内,出栈的过程就对应着从尾到头

/**
*    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<>();
        while (listNode != null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> res = new ArrayList<>();
        while(!stack.isEmpty()){
            res.add(stack.pop());
        }
        return res;
    }

}

 

<剑指offer> 第3题

标签:port   null   color   import   off   print   入栈   arraylist   new   

原文地址:https://www.cnblogs.com/HarSong13/p/11000722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!