美文网首页
从尾到头打印链表——jzoffer

从尾到头打印链表——jzoffer

作者: 二十岁的弹簧 | 来源:发表于2018-12-04 08:57 被阅读0次

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

    通过题目可以知道,我们需要遍历链表,从尾到头打印,是“先入后出”的模式,可以用栈来管理数据

    class Solution:
        def reversingly_iteratively(self, head):
            if head is None:
                return None
            stack = [head.value]
            node = head
            while node.next is not None:
                stack.append(node.next.value)
                node = node.next
            while stack is not None:
                yield stack.pop()
    

    既然想到了用栈实现这个函数,而递归本质上就是一个栈结构。要实现反过来输出链表,我们每访问一个节点的时候,先递归输出它后面的结点,再输出该节点自身,这样链表的输出结果就反过来了。当链表非常长的时候,就会导致函数调用的层级很深,从而有可能导致函数调用栈溢出。

    class Solution:
        def reversingly_recursively(self, head):
            if head is None:
                return None
            if head.next is None:
                print(head.value, end=' ')
            else:
                self.reversingly_recursively(head.next)
    

    相关文章

      网友评论

          本文标题:从尾到头打印链表——jzoffer

          本文链接:https://www.haomeiwen.com/subject/rawpcqtx.html