《劍指offer:Java版》 輸入一個鏈表,按鏈表從尾到頭的順序返回一個ArrayList

描述:

輸入一個鏈表,按鏈表從尾到頭的順序返回一個ArrayList

實現:

package com.ma.offer;

import java.util.ArrayList;
import java.util.Stack;

/**
 * 輸入一個鏈表,按鏈表從尾到頭的順序返回一個ArrayList。
 */
class ListNode {
    int val;
    ListNode next;
    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
public class Demo03 {
    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode){
        if(listNode==null){
            ArrayList list=new ArrayList();
            return list;
        }

        Stack<Integer> stk=new Stack<Integer>();
        while(listNode!=null){
            stk.push(listNode.val);
            listNode=listNode.next;
        }

        ArrayList<Integer> arr=new ArrayList<Integer>();
        while(!stk.isEmpty()){
            arr.add(stk.pop());

        }
        return arr;
    }
    public static void main(String[] args) {
        // 調用方法
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章