zoukankan      html  css  js  c++  java
  • 【剑指offer】03 从尾到头打印链表

    题目描述

    输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

    分析

    1.存到列表中,直接反向输出

    2.栈的实现

    3.递归。先进到最里面一层取出值,再一层一层出来

    解题

    1.

    class Solution:
        # 返回从尾部到头部的列表值序列,例如[1,2,3]
        def printListFromTailToHead(self, listNode):
            # write code here
            l = []
            head = listNode
            while head:
                l.append(head.val)
                head = head.next
            #l.reverse()
            return(l[::-1])

    2、

    class Solution:
        # 返回从尾部到头部的列表值序列,例如[1,2,3]
        def printListFromTailToHead(self, listNode):
            # write code here
            l = []
            head = listNode
            while head:
                l.append(head.val)
                head = head.next
            #l.reverse()
            stack=[]
            while l:
                stack.append(l.pop())
            return(stack)

     3、

    class Solution:
        # 返回从尾部到头部的列表值序列,例如[1,2,3]
        def printListFromTailToHead(self, listNode):
            result = []
            def solutions(Node):
                if Node:
                    solutions(Node.next)
                    result.append(Node.val)
            # write code here
            solutions(listNode)
            return result
  • 相关阅读:
    PMO的重要性
    idea CPU过高问题
    近期面试心得
    Spring-Eureka
    BIO/NIO
    redis redlock
    nmon 安装及使用 【linux环境】
    一致性hash 算法
    gossip协议了解
    00008
  • 原文地址:https://www.cnblogs.com/fuj905/p/12747490.html
Copyright © 2011-2022 走看看