排序双链表Python

时间:2011-01-06 02:33:32

标签: python linked-list

我无法理解和实施双向链接列表。我可以掌握链表的大部分概念。这是我到目前为止的代码(在Python中)

*这是纯粹的学术练习。我通常会使用list和dict。

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])

1 个答案:

答案 0 :(得分:2)

将循环更改为

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作为属性不是问题,因为它限定了名称,以便不会发生阴影。但它会在某些语法高亮显示器中陷入困境。