首页 > 其他 > 详细

【剑指offer】03 从尾到头打印链表

时间:2020-04-21 21:14:54      阅读:67      评论:0      收藏:0      [点我收藏+]

题目描述

输入一个链表,按链表从尾到头的顺序返回一个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

 

【剑指offer】03 从尾到头打印链表

原文:https://www.cnblogs.com/fuj905/p/12747490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!