【算法题之路】从尾到头打印链表

    xiaoxiao2021-04-14  45

    利用 栈 先进后出 的特性 是最佳方法 链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035 来源:牛客网 /** *    public class ListNode { *        int val; *        ListNode next = null; * *        ListNode(int val) { *            this.val = val; *        } *    } * */ import java.util.Stack; import java.util.ArrayList; public class Solution {     public 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;     } }
    转载请注明原文地址: https://ju.6miu.com/read-670415.html

    最新回复(0)