我正在尝试创建一个Doubly LinkedList,但我得到的是内存位置,而不是Node值。感谢的帮助
#!/usr/bin/python3
class Node:
def __init__(self, num):
self.next = None
self.prev = None
self.num = num
class DlinkedList:
def __init__(self):
self.start = None
self.end = None
self.size = 0
def addFirst(self, num):
n = Node(num)
if( self.start == None):
self.start = n
self.end = n
print (self.start)
print (self.end)
print (self.size)
else:
n.next = self.start
d = DlinkedList()
print ("Add node 2")
d.addFirst(2)
print ("Add Node 1")
d.addFirst(1)
输出如下所示,这意味着我在这里做错了什么。
我知道代码还不完整,但我正在尝试一点一点地开始
代码的输出为:
Add node 2
<__main__.Node object at 0x7f0c61219940>
<__main__.Node object at 0x7f0c61219940>
0
Add Node 1
这里似乎缺少一些关键步骤。您需要确保递增计数器,并在新节点中链接到双链接列表的前面。以下是我最终得到的:
#!/usr/bin/python3
class Node:
def __init__(self, num):
self.next = None
self.prev = None
self.num = num
class DlinkedList:
def __init__(self):
self.start = None
self.end = None
self.size = 0
def addFirst(self, num):
n = Node(num)
if(self.start == None):
self.start = n
self.end = n
print (self.start.num)
print (self.end.num)
print (self.size)
else:
n.next = self.start
self.start.prev = n
self.start = n
self.size += 1
d = DlinkedList()
print ("Add node 2")
d.addFirst(2)
print ("Add Node 1")
d.addFirst(1)
print(d.start.num, d.start.next.num, d.end.prev.num, d.end.num)
iPython 的输出示例
Add node 2
2
2
0
Add Node 1
1 2 1 2
In [3]: d.addFirst(3)
In [4]: print(d.start.num, d.start.next.num, d.end.prev.num, d.end.num)
3 1 1 2
您正在打印类型为Node
的self.start
和self.end
,由于Node
没有__str__
覆盖,它只打印内存位置。您要做的是打印self.start.num
和self.end.num
,或者添加__str__
:的定义
def __str__(self):
return self.num