简体   繁体   English

递归深度超出-Python双链接列表

[英]Recursion Depth Exceeded - Python Doubly-Linked List

I'm in the process of creating a FIFO implemented as a doubly-linked list, but I'm at a loss as to why I'm receiving a recursion error. 我正在创建一个实现为双链表的FIFO,但是对于为什么收到递归错误我一无所知。 I've posted my code and the error I received below. 我已经发布了我的代码和下面收到的错误。 Any help would be much appreciated! 任何帮助将非常感激!

"""DLList.py"""

class DLList(object):
    """A doubly-linked list

    attributes: nl = node list"""
    def __init__(self, nl=[]):
        self.nl = nl

    def __str__(self):
        return str(self.nl)

    def __len__(self):
        return len(self.nl)

    def append(self, node):
        if not isinstance(node, DLNode):
            raise TypeError
        try:
            node.pn = self.nl[-1]
            node.pn.nn = node
            self.nl.append(node)
        except:
            self.nl.append(node)

    def pop(self):
        rn = self.nl.pop(0)
        try:
            self.nl[0].pn = None
        except:
            pass
        return rn


class DLNode(object):
    """A node in a doubly-linked list.

    attributes: self.pn = previous node, self.data = data, self.nn = next node"""
    def __init__(self, data):
        self.pn = None
        self.data = data
        self.nn = None

    def __str__(self):
        return '[%s, %s, %s]' % (self.pn, self.data, self.nn)


a = DLNode(17)
b = DLNode(15)
c = DLNode(12)
d = DLNode(46)
e = DLNode(46)

ages = DLList()
ages.append(a)
ages.append(b)
ages.append(c)
ages.append(d)
ages.append(e)

print ages.pop()

I received this error: 我收到此错误:

File "C:\python\swampy-2.0\DLList.py", line 43, in __str__
    return '[%s, %s, %s]' % (self.pn, self.data, self.nn)
RuntimeError: maximum recursion depth exceeded

The thing is, I never intended to use recursion, and I can't figure out why I've entered into a recursive loop. 事实是,我从未打算使用递归,而且我不知道为什么进入了递归循环。 ages.pop() is meant to return an instance of DLNode. ages.pop()用于返回DLNode的实例。

When you print the node, you are trying to print self.pn and self.nn. 当您打印节点时,您正在尝试打印self.pn和self.nn。 Each of those is a reference to another node, which when printed will try to print its next node and previous node, and so on, ad infinitum. 每个节点都是对另一个节点的引用,该节点在打印时将尝试无限制地打印其下一个节点和上一个节点,依此类推。 You are asking to print an infinite hall of mirrors of nodes. 您要打印一个无限的节点镜像大厅。

You have nothing keeping track of what has already been printed, so the recursion will continue forever. 您无法跟踪已经打印的内容,因此递归将永远继续。

Maybe I recommend using collections.deque instead? 也许我建议改用collections.deque You can read its documentation in the library . 您可以在库中阅读其文档。 Unless you are writing your implementation as an academic exercise, deque is probably better. 除非您将实现写成学术练习,否则deque可能更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM