zoukankan      html  css  js  c++  java
  • 剑指:从尾到头打印链表

    题目描述

    输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。

    返回的结果用数组存储。

    样例

    输入:[2, 3, 5]
    返回:[5, 3, 2]
    

    解法一:利用栈(后进先出)

    遍历链表,每个链表结点值 push 进栈,最后将栈中元素依次 pop 到数组中。

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
    
        /**
         * 从尾到头打印链表
         *
         * @param head 链表头结点
         * @return 结果数组
         */
        public int[] printListReversingly(ListNode head) {
            if (head == null) {
                return null;
            }
            Stack<Integer> stack = new Stack<>();
            ListNode cur = head;
            int cnt = 0;
            while (cur != null) {
                stack.push(cur.val);
                cur = cur.next;
                ++cnt;
            }
    
            int[] res = new int[cnt];
            int i = 0;
            while (!stack.isEmpty()) {
                res[i++] = stack.pop();
            }
            return res;
        }
    }

    解法二:递归

    递归的本质也是一个栈结构,每访问一具结点的时候,先递归输出后面的结点,再输出该结点自身。

    /**
    *    public class ListNode {
    *        int val;
    *        ListNode next = null;
    *
    *        ListNode(int val) {
    *            this.val = val;
    *        }
    *    }
    *
    */
    import java.util.ArrayList;
    public class Solution {
        ArrayList<Integer> arrayList=new ArrayList<Integer>();
            public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
                if(listNode!=null){
                    printListFromTailToHead(listNode.next);
                    arrayList.add(listNode.val);
                }
                return arrayList;
            }
    }
  • 相关阅读:
    C# Sleep延时方法
    浅谈模糊测试
    python time模块常用方法小结
    Markdown使用小结
    关于测试用例设计、评审及用例质量评估的思考
    关于评估软件产品质量的思考
    关于软件测试工程师进阶提升的思考
    关于软件测试中回归测试的思考
    测试技术的思考 ---- 读《微软的软件测试之道》有感系列
    vue-learning:22
  • 原文地址:https://www.cnblogs.com/lisen10/p/11041256.html
Copyright © 2011-2022 走看看