简体   繁体   English

如何在Python中将双重链接列表实现到我的树形结构中?

[英]How can I implement doubly linked lists into my tree structure in Python?

So I'm trying to represent an XML file using python. 因此,我尝试使用python表示XML文件。 I already managed to do that. 我已经设法做到了。 But each child node in my tree has to be doubly linked and I don't know how to do that. 但是我树中的每个子节点都必须双重链接,我不知道该怎么做。 I've found a few examples of code online but they all use classes and the professor doesn't want us using classes. 我在网上找到了一些代码示例,但它们都使用类,而教授不希望我们使用类。 Here's my code: 这是我的代码:

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

For those of you wondering, the purpose of this project is to create a rooted tree with unbounded branching. 对于那些想知道的人来说,该项目的目的是创建带有无限分支的根树。 I hope that once I can implement the doubly linked list I will be able to add a child node within a child node. 我希望一旦实现了双向链接列表,便能够在子节点中添加一个子节点。

You should be able to implement a linked list using lists. 您应该能够使用列表实现链接列表。 You can define each element as a list with the element itself, the item before it, and the item after it. 您可以将每个元素定义为一个列表,其中包含元素本身,元素之前的项目以及元素之后的项目。 If the list contains the previous node, the next node, and the element itself, respectively, and the head is stored in head , the syntax to append newElement to the beginning of the list would be as follows: 如果列表分别包含上一个节点,下一个节点和元素本身,并且head存储在head ,则将newElement追加到列表开头的语法如下:

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

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

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