Python 如何创建一个方法来显示带有数据和指向屏幕上下一个节点的指针的链表?

Python 如何创建一个方法来显示带有数据和指向屏幕上下一个节点的指针的链表?,python,linked-list,Python,Linked List,我已经创建了一个类节点来创建一个节点,还有一个类单列表来创建一个链表。 在singlelist类中,我创建了append方法来向链表添加一个新节点如何创建一个方法,在屏幕上打印链接列表,显示节点的数据及其指向的位置 这是我的链表代码: class Node: def __init__(self , data , next ): self.data = data self.next = next class singlelist: head =

我已经创建了一个类节点来创建一个节点,还有一个类单列表来创建一个链表。
在singlelist类中,我创建了append方法来向链表添加一个新节点
如何创建一个方法,在屏幕上打印链接列表,显示节点的数据及其指向的位置

这是我的链表代码:

class Node:
    def __init__(self , data , next ):
        self.data = data
        self.next = next

class singlelist:
    head = None
    tail = None

    def append(self , data):
        node = Node(data , None)
        if self.head is None:
            self.head=self.tail=node
        else:
            self.tail.next=node
        self.tail=node

您可以这样做:
在类中创建show方法:

def show(self):
    cur_node = self.head         #cur_node is your current node
    while cur_node is not None:
        print(cur_node.data , "-> " , end = "" )
        cur_node = cur_node.next
    print(None)

如果要使用
print
函数打印类的对象,可以在类中定义名为
\uuuu str\uuuu(self)
的方法

对于这个特定的链表,我会这样做:

def __str__(self):
    return_str = ""
    iterator = self.head
    while iterator != None:
        return_str += iterator.data + ", "
        iterator = iterator.next
    return return_str
myList = singleList()
print(myList)
然后,您可以像这样打印singleList对象:

def __str__(self):
    return_str = ""
    iterator = self.head
    while iterator != None:
        return_str += iterator.data + ", "
        iterator = iterator.next
    return return_str
myList = singleList()
print(myList)

你几乎肯定不想做
类级变量。我同意。定义一个
\uuuu init\uuuu(self)
方法,并在其中声明
self.head=None
self.tail=None
。好的,谢谢,我收到了!!打印语句中使用
end=”“
的原因可能重复?@secureamd2,在每个输出的末尾添加一个空字符串,而不是换行符。它只是确保整个列表的输出都在一行上,而不是每个节点都打印在自己的行上。