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;
            }
    }
  • 相关阅读:
    LOJ#2245 魔法森林
    洛谷P1173 [NOI2016]网格
    [NOI2018]归程
    宇宙旅行
    hdu 4027 Can you answer these queries?(线段树)
    poj 1661 Help Jimmy(记忆化搜索)
    hdu 1078 FatMouse and Cheese(简单记忆化搜索)
    poj 3616 Milking Time (基础dp)
    hdu 1074 Doing Homework(状压dp)
    codeforces 735C. Tennis Championship(贪心)
  • 原文地址:https://www.cnblogs.com/lisen10/p/11041256.html
Copyright © 2011-2022 走看看