简体   繁体   English

关于python中的链表

[英]About linked lists in python

I need to create a function to remove a node from a linked list from a value given manually inside this function but I don't know exactly how to do that.我需要创建一个函数,以从该函数内部手动给出的值中从链表中删除节点,但我不知道如何做到这一点。 My algorithm is like this:我的算法是这样的:

noRaiz = None

def novoNo(valor):
    return {
        "valor": valor,
        "proximo": None
    }
def remove(valor):
global noRaiz
if noRaiz is None:
    return
noAtual = noRaiz
if noRaiz["valor"] == valor:
    noRaiz = noRaiz["proximo"]


def imprimir():
    noAtual = noRaiz
    while noAtual is not None:
        print(noAtual["valor"])
        noAtual = noAtual["proximo"]


noRaiz = novoNo(54)
no2 = novoNo(26)
no3 = novoNo(93)
no4 = novoNo(17)
no5 = novoNo(77)
no6 = novoNo(31)

noRaiz["proximo"] = no2
no2["proximo"] = no3
no3["proximo"] = no4
no4["proximo"] = no5
no5["proximo"] = no6
no6["proximo"] = None


imprimir()

noRaiz is the first node on the list, noAtual is the current node in the list at print time when running the code and imprimir() it's the function to print the nodes. noRaiz 是列表中的第一个节点, noAtual 是运行代码时打印时列表中的当前节点, imprimir() 是打印节点的函数。 What would the function look like if I wanted to remove node 54 or 17?如果我想删除节点 54 或 17,函数会是什么样子?

The trick is to move through the linked list and look one node ahead for a match with the value.诀窍是遍历链表并在前面查找一个节点以查找与该值匹配的节点。 When there is a match, you should alter the link of your current node so that it skips that next node having the value.当匹配时,您应该更改当前节点的链接,以便它跳过具有该值的下一个节点。

Here is the function:这是函数:

def remove(valor):
    global noRaiz
    if noRaiz is None:  # Nothing to do
        return
    noAtual = noRaiz
    if noRaiz["valor"] == valor:  # Special case
        noRaiz = noRaiz["proximo"]
        return
    while noAtual["proximo"] is not None:
        if noAtual["proximo"]["valor"] == valor:
            noAtual["proximo"] = noAtual["proximo"]["proximo"]
            break
        noAtual = noAtual["proximo"]

Remark: consider implementing your linked list with a Node class instead of a global dictionary.备注:考虑使用 Node class而不是全局字典来实现您的链表。

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

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