Python:Linklist deque addfront&add

2024-10-05 21:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者,现在我在这个程序中遇到了一个问题。

首先,这里是NodeList:<;-linklist

class Node:

    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

下面是我的节目:

^{pr2}$

当我在addFrontDLL中添加一个项目时,一切都很好。但是在addredll中添加一个项目后,它的类似项将添加到另一个容器中。然后我尝试再次使用addFrontDLL添加,它可以处理我想要的方式(该项添加到另一个容器上)。请参见下图:

enter image description here

我希望有人替我解释并解决。如有任何帮助,将不胜感激。非常感谢。


Tags: 项目ltself程序datareturndef容器
1条回答
网友
1楼 · 发布于 2024-10-05 21:57:25

问题是,第一次添加前面有addFrontDLL的节点时,没有设置DequeLL.last字段。您的addRearDLL确实正确地处理了添加新节点的问题,这就是为什么在后面添加之后一切都会正常工作。在

试试这个:

class DequeLL:

    def __init__(self):
        self.head = None
        self.last = None
        self.length = 0

    def __str__(self): # Refactored for clarity
        width = (max(len(node.data) for node in self.allNodes()) 
                    if self.head else 0) # width to avoid ambiguity with self.length
        s = ['\u2510{}\u250c'.format(' '*width)]
        for node in self.allNodes():
            s.append('\u2502{:<{}}\u2502'.format(node.data, width))
        s.append('\u2514{}\u2518'.format('\u2500'*width))
        return '\n'.join(s)

    def addFrontDLL(self, item):
        temp = Node(str(item))
        temp.setNext(self.head)
        self.head = temp
        if self.last is None: # if adding to an empty deque, set the last node, too
            self.last = temp
        self.length += 1
        print(self) # refactored the pretty-printing into __str__ for clarity

    def addRearDLL(self, item):
        node = Node(str(item))
        node.next = None
        if self.length == 0:
            self.head = self.last = node
        else:
            last = self.last
            last.next = node
            self.last = node
        self.length = self.length + 1 
        print(self)

    def allNodes(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next

示例的输出现在是:

^{pr2}$

相关问题 更多 >