![](/img/trans.png)
[英]How do I set the prev of my first node to the next of my last node to create a circular doubly linked list?
[英]How can I create a method to show linked list with data and pointer to next node on screen?
我创建了一个类Node ,它创建一个节点,并创建了类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
功能print
类的对象,则可以在类中定义一个称为__str__(self)
的方法。
对于此特定的链接列表,我将执行以下操作:
def __str__(self):
return_str = ""
iterator = self.head
while iterator != None:
return_str += iterator.data + ", "
iterator = iterator.next
return return_str
然后,您可以只打印一个singleList对象,如下所示:
myList = singleList()
print(myList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.