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

2024-09-27 21:26:30 发布

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

我已经创建了一个类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

Tags: 方法selfnonenodedata节点defhead
2条回答

你可以这样做:
在类中创建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函数打印类的对象,可以在类中定义名为__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)

相关问题 更多 >

    热门问题