剑指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]
全部评论

相关推荐

点赞 评论 收藏
分享
代码飞升_不回私信人...:别这样贬低自己,降低预期,放平心态,跟昨天的自己比。做好自己,反而会效率更高心态更好,加油兄弟
点赞 评论 收藏
分享
评论
32
9
分享

创作者周榜

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