[英]Printing a node in a linked list
I'm very new to coding and I have a basic question about printing a node in a doubly linked list in Python. 我对编码非常陌生,我有一个基本问题,想在Python中的双向链表中打印节点。
class Node():
def __init__(self, key = None, prev = None, next = None):
self.key = key
self.prev = prev
self.next = next
def __str__(self):
return ('[%s][%d][%s]' % (repr(self.prev), self.key, repr(self.next)))
Obviously I then have some more code for the list class itself. 显然,我然后为列表类本身提供了更多代码。 Let's say I have a doubly linked list with two nodes: 假设我有一个带有两个节点的双链表:
node1 : key 21 节点1 :密钥21
node2 : key 10 节点2 :密钥10
head --> node1 <==> node2 头->节点1 <==>节点2
If I do print(node1) I get: 如果我打印(node1),我得到:
[*location of prev node*][21][*location of next node*]
which works exactly how I want. 正是我想要的。
So 2 questions: 所以有两个问题:
Is this code "messy" or acceptable syntax for the str method? 此代码是“混乱”的还是str方法可接受的语法?
Instead of printing the location of the prev and next nodes, how would I print the names of the nodes instead eg [node7][82][node9]
? 我将不打印上一个和下一个节点的位置 ,而是打印这些节点的名称 ,例如[node7][82][node9]
?
Hope this makes sense, and thanks for any help! 希望这有道理,并感谢您的帮助!
Instead of having to create a self.name
needed to be initialized for each Node
. 不必创建需要为每个Node
初始化的self.name
。 You could add a self.id
initialized with a static counter
incremented at each creation. 您可以添加一个self.id
,并使用每次创建时增加的静态counter
初始化。
Step 1 - add a static counter
and initialize the self.id
attribute 步骤1-添加静态counter
并初始化self.id
属性
The counter
starts from 0
and is accessible through Node.counter
. counter
从0
开始,可以通过Node.counter
访问。
class Node():
counter = 0
def __init__(self, key = None, prev = None, next = None):
Node.counter += 1
self.id = Node.counter
self.key = key
self.prev = prev
self.next = next
Step 2 - modify the __str__
function to get the id
of prev
and next
第2步 -修改__str__
函数以获取prev
和next
的id
The name of the self.prev
and self.next
is only displayed when not None
. self.prev
和self.next
的名称仅在不为None
时显示。
Recover the name of the class with self.__class__.__name__
. 使用self.__class__.__name__
恢复类的名称。
def __str__(self):
sprev = repr(self.prev)
if self.prev != None :
sprev = '%s%d' % (self.__class__.__name__, self.prev.id)
snext = repr(self.next)
if self.next != None :
snext = '%s%d' % (self.__class__.__name__, self.next.id)
return ('[%s][%d][%s]' % (sprev, self.key, snext))
Here are some examples: 这里有些例子:
>>> node1 = Node(21)
>>> print(node1)
[None][21][None]
>>> node2 = Node(10,node1)
>>> print(node2)
[Node1][10][None]
>>> node3 = Node(11,node2,node1)
>>> print(node3)
[Node2][11][Node1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.