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

    题目:输入一个链表,从尾到头打印链表每个节点的值。 

    思路:链表是不可以随机访问的,所以如果不借助辅助空间的话,每打印一个节点就会遍历一遍链表,时间复杂度为O(n^2)。那么就需要以空间换取时间,因为是倒着遍历链表,所以栈是最好的选择。只需要遍历一遍链表入栈。然后遍历栈,出栈。这样时间复杂度为O(n)。

    实现代码:

    /**
    *    public class ListNode {
    *        int val;
    *        ListNode next = null;
    *
    *        ListNode(int val) {
    *            this.val = val;
    *        }
    *    }
    *
    */
    import java.util.*;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            if(listNode == null)
                return new ArrayList<Integer>();
            Stack<Integer> stack = new Stack<Integer>();
            ArrayList<Integer> ret = new ArrayList<Integer>();
            ListNode head = listNode;
            while(head != null) {
                stack.push(head.val);
                head = head.next;
            }
            while(!stack.isEmpty()) {
                ret.add(stack.pop());
            }
            return ret;
        }
    }
  • 相关阅读:
    Power BI
    Power BI
    gulp的常用api
    关于promise
    webapp思路和rem适配极其viewport
    react初识
    node基础再现--module.exports 和exports
    sublime的js调试环境(基于node环境)
    题解 poj2778 DNA Sequence
    题解 TJOI/HEOI2016 字符串
  • 原文地址:https://www.cnblogs.com/wxisme/p/5236151.html
Copyright © 2011-2022 走看看