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;
            }
    }
  • 相关阅读:
    WeChat小程序开发(五、前端总结)
    前端实现复制到剪贴板
    vue的自定义指令含大写字母会失效
    如何把网页变成黑白
    原生JS offsetX和offsetY引起抖动
    jQuery中prop方法和attr方法区别
    Js for循环中的闭包 & let和var的混用对比
    html和body标签默认高度为0带来的影响
    JS字符串数组降维
    CSS浮动流脱标的字围现象
  • 原文地址:https://www.cnblogs.com/lisen10/p/11041256.html
Copyright © 2011-2022 走看看