Python 无序列表与节点:__str__方法



我正在尝试为我的UnorderedList类编写一个__str__method,该类可以允许以如下格式打印列表:[1,2,3,4,5]。

但出于某种原因,它只是打印出列表的第一个位置。[1] 而不是 [1,2,3,4,5]

def __str__(self):
    result = "["
    node = self.head
    if node != None:
        result += str(node.data)
        node = node.next
        for i in range(self.num_elements - 1):
            result += ", " + str(node.data)
            node = node.next
    result += "]"
    return result    

这是我的其余节点和无序列表类方法...

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

class UnorderedList:
def __init__(self):
    self.head = None
def isEmpty(self):
    return self.head == None
def add(self,item):
    temp = Node(item)
    temp.setNext(self.head)
    self.head = temp
def size(self):
    current = self.head
    count = 0
    while current != None:
        count = count + 1
        current = current.getNext()
    return count
def search(self,item):
    current = self.head
    found = False
    while current != None and not found:
        if current.getData() == item:
            found = True
        else:
            current = current.getNext()
    return found
def remove(self,item):
    current = self.head
    previous = None
    found = False
    while not found:
        if current.getData() == item:
            found = True
        else:
            previous = current
            current = current.getNext()
    if previous == None:
        self.head = current.getNext()
    else:
        previous.setNext(current.getNext())
def __str__(self):
    result = "["
    node = self.head
    if node != None:
        result += str(node.data)
        node = node.next
        for i in range(0 - 1):
            result += ", " + str(node.data)
            node = node.next
    result += "]"
    return result

任何帮助都会很棒。另外,我觉得有一种更简单的方法来编写str

您的循环不正确(在顶部版本中使用从未设置的self.num_elements和在底部版本中强制循环永远不会发生,因为range(0 - 1) AKA range(-1)当然是[]。 可能更好:

def __str__(self):
    result = "["
    node = self.head
    if node != None:
        result += str(node.data)
        node = node.next
        while node:
            result += ", " + str(node.data)
            node = node.next
    result += "]"
    return result    

区别在于循环while node:,而不是以某种方式试图占卜或强制所涉及的元素数量。

def __str__(self):
    result = "["
    node = self.head
    while node:
        result += ('' if result == '[' else ", ") + str(node.data)
        node = node.next
    result += "]"
    return result

相关内容

  • 没有找到相关文章

最新更新