这是我的双链表deque python代码的一部分.

编写的"appendleft"函数几乎与"append"函数类似,通常是输出.为什么最后一个"append('apple')"代码不能在"Group_of_append"函数中正常输出?

class Node:

    def __init__(self,item,prev,next):

        self.item = item
        self.prev = prev
        self.next = next

class deque:

    def __init__(self,name):

        self.name = name
        self.head = Node(None,None,None)
        self.tail = Node(None,self.head,None)

        self.head.next = self.tail
        self.size = 0

    def append(self,item):
        current = self.head
        new_node = Node(item,None,None)
        while current.next != None:
            current = current.next
        current.next = new_node
        new_node.prev = current
        self.tail = new_node
        self.size += 1
        return
    
    def appendleft(self,item):
        current = self.tail
        new_node = Node(item,None,None)
        while current.prev != None:
            current = current.prev
        current.prev = new_node
        new_node.next = current
        self.head = new_node
        self.size += 1
        return

    def print_list(self): 

        p = self.head

        while p.next != None:
            if p.item == None:
                pass
            else:
                print(p.item,end=' ')
            
            p = p.next

    def Group_of_append(self):
        print('Group_of_append')
        self.append('graphe')
        self.append('cherry')
        self.append('apple')
        self.appendleft('watermelon')
        self.appendleft('strawberry')
        self.print_list()
        print(" ")

deq = deque('name')
deq.Group_of_append()

结果是

strawberry watermelon graphe cherry

_append的组_上的最后一个append代码是self.append('apple')无效.

在定义"append"函数时,我认为由于多了一个大小不够,所以不会有输出.

所以,我改变了deque上的'append'函数,如下所示

    def append(self,item):
        self.size += 1
        current = self.head
        new_node = Node(item,None,None)
        while current.next != None:
            current = current.next
        current.next = new_node
        new_node.prev = current
        self.tail = new_node
        self.size += 1
        return

但结果是一样的(仍然是最新的"append"函数不打印任何内容)

strawberry watermelon graphe cherry

推荐答案

你的附件很好用.问题在于print_list函数,当p.nextNone时停止.这意味着你的最后一个元素不会被打印,因为它的下一个元素是None.

总而言之,你对这个列表的逻辑非常奇怪,可能需要大量返工,这会让你更容易发现像这样的错误.例如,即使在deque对象中有可用的头部和尾部,也可以在追加时遍历整个列表.

Python相关问答推荐

在Python中,什么表达相当于0x1.0p-53?

在Python中使用一行try

从 struct 类型创建MultiPolygon对象,并使用Polars列出[list[f64]列

Tkinter -控制调色板的位置

将行从一个DF添加到另一个DF

有什么方法可以避免使用许多if陈述

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

即使在可见的情况下也不相互作用

在Pandas DataFrame操作中用链接替换'方法的更有效方法

如何让Flask 中的请求标签发挥作用

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

使用@ guardlasses. guardlass和注释的Python继承

如何更改分组条形图中条形图的 colored颜色 ?

ODE集成中如何终止solve_ivp的无限运行

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

NumPy中条件嵌套for循环的向量化

多处理队列在与Forking http.server一起使用时随机跳过项目

计算天数

如何使用两个关键函数来排序一个多索引框架?

为什么调用函数的值和次数不同,递归在代码中是如何工作的?