剑指offer官方题解 (python)

从尾到头打印链表

http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        # 方法一  使用栈
        if not listNode:
            return []
        temp = []
        result = []
        while listNode: 
            temp.append(listNode.val) # 进栈
            listNode = listNode.next
        while temp:
            result.append(temp.pop()) # 出栈
        return result

            # 方法二  使用递归
        result = []
        def solutions(Node):
            if Node:
                solutions(Node.next)
                result.append(Node.val)
        solutions(listNode)
        return result

        # 方法三 使用从头到尾遍历,逆序输出
        result = []
        while listNode:
            result.append(listNode.val)
            listNode = listNode.next
        return result[::-1]
全部评论

相关推荐

Beeee0927:是缅甸园区吗
点赞 评论 收藏
分享
程序员小白条:这比例牛逼,750:1
点赞 评论 收藏
分享
昨天 12:15
门头沟学院 Java
点赞 评论 收藏
分享
评论
32
9
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务