【问题标题】:Sorted Doubly Linked List Python排序的双向链表 Python
【发布时间】:2011-01-06 02:33:32
【问题描述】:

我在理解和实现双向链表时遇到了麻烦。我可以掌握链表的大部分概念。到目前为止,这是我的代码(在 Python 中)

*这是一个纯粹的学术练习。我通常会使用列表和字典。

class DoublyNode(object):
    """A node of the SortedDoublyLL object.

    DoublyNode(item, next=None, previous=None) -> a new DoublyNode with data as
    its data, and next and previous as its neighbors."""

    def __init__(self, data, next = None, previous = None):
        """Make a new DoublyNode from item, pointing to next and previous."""

        self.data = data
        self.next = next
        self.previous = previous

class SortedDoublyLL(object):
    """A Sorted Doubly Linked List.

    SortedDoublyLL() -> new SortedDoublyLL list that is empty
    SortedDoublyLL(sequence) -> a SortedDoublyLL initialized from sequence's
    items.

    """

    def __init__(self, sequence = []):
        """Make a new SortedDoublyLL from the elements of sequence."""

        if len(sequence) == 0:
            self.head = None
            self.tail = None
        else:
            cur_node = None
            prev_node = None
            sequence.sort()
            sequence.reverse()
            for element in sequence:
                prev_node = cur_node
                cur_node = DoublyNode(element, cur_node, prev_node)

            self.head = cur_node
            self.tail = DoublyNode(sequence[0])

【问题讨论】:

  • 我认为你最好先用一个元素设置链表,然后使用插入算法找到插入其他元素的正确位置。如果您想保持简单,请一开始。

标签: python linked-list


【解决方案1】:

将循环更改为

for element in sequence:
    prev_node = cur_node
    cur_node = DoublyNode(element, None, prev_node)
    prev_node.next = cur_node

因为prev_node = cur_node 行在调用DoublyNode(element, cur_node, prev_node) 之前,所以您最终会将前一个元素和下一个元素都设置为前一个元素,因此您最终会得到一个只有两个指向前一个元素的链接的链表。因此,您不妨将None 作为next 参数1 传递,然后在循环的下一次传递中手动初始化它。这样做的好处是在列表的最后一个元素上将其保留为 None

1 在构造函数中使用名称 next 作为参数将隐藏内置函数 next,该函数推进迭代器。您可以使用名称next_,这是规范的做法。使用next 作为属性不是问题,因为它限定了名称,因此不会发生阴影。不过,它会在一些语法荧光笔中搞砸。

【讨论】:

    猜你喜欢
    • 2014-02-04
    • 2022-01-09
    • 2018-11-04
    • 1970-01-01
    • 2012-03-30
    • 2011-04-13
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多