倒序打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值。
 1 /**
 2 *    public class ListNode {
 3 *        int val;
 4 *        ListNode next = null;
 5 *
 6 *        ListNode(int val) {
 7 *            this.val = val;
 8 *        }
 9 *    }
10 *
11 */
12 import java.util.Stack;
13 import java.util.ArrayList;
14 public class Solution {
15     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
16       Stack<Integer> q=new Stack<Integer>();
17         ArrayList<Integer> list=new ArrayList<Integer>();
18         if(listNode==null){
19            return list; 
20         }
21         while(listNode!=null){
22             q.push(listNode.val);
23             listNode=listNode.next;
24         }
25         
26          
27         while(!q.isEmpty()){
28            list.add(q.pop());
29         }
30         return list;
31     }
32 }

猜你喜欢

转载自www.cnblogs.com/4545mdf/p/9022184.html
今日推荐