【问题标题】:How can I implement doubly linked lists into my tree structure in Python?如何在 Python 中将双向链表实现到我的树结构中?
【发布时间】:2015-10-26 00:05:41
【问题描述】:

所以我正在尝试使用 python 表示一个 XML 文件。我已经设法做到了。但是我的树中的每个子节点都必须是双重链接的,我不知道该怎么做。我在网上找到了一些代码示例,但它们都使用类,教授不希望我们使用类。这是我的代码:

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as etree


def create_tree(): #This function creates the root element of my tree
    n = input("Enter your root Element: ")
    root = Element(n)
    tree = ElementTree(root)
    print(etree.tostring(root))
    return root

def add_child():
    root = create_tree()
    new = True
    while new == True:
        ask = input("If you wish to add a new child type 'yes', else type something else: ")
        if ask == 'yes':
            n = input("Enter the name of the node: ") #This block of code creates a child and appends it to the root element
            node = Element(n)
            root.append(node)
            print(etree.tostring(root))
        else:
            break
    return etree.tostring(root)
add_child()

对于那些想知道的人,这个项目的目的是创建一个具有无限分支的有根树。我希望一旦我可以实现双向链表,我将能够在子节点中添加一个子节点。

【问题讨论】:

    标签: python data-structures tree


    【解决方案1】:

    您应该能够使用列表实现链表。你可以定义 每个元素作为一个列表,其中包含元素本身、它之前的项目和它之后的项目。如果列表分别包含前一个节点、下一个节点和元素本身,并且头部存储在head 中,则将newElement 附加到列表开头的语法如下:

    newNode = [None,head,newElement]
    head[0] = newNode
    head = newNode
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 2015-07-27
      • 2012-05-10
      • 2015-05-16
      • 2019-05-02
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多