我已经创建了一个类Node来创建一个节点,还有一个类singlelist来创建一个链表。
在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方法:
如果要使用
print
函数打印类的对象,可以在类中定义名为__str__(self)
的方法。你知道吗对于这个特定的链表,我会这样做:
然后,您可以像这样打印一个singleList对象:
相关问题 更多 >
编程相关推荐