python链接列表在打印时接收内存地址的问题,除非双调用
我正在创建一个链接的列表实现,我无法修复必须double Call node.val.val.val.val
打印数据而不是内存地址的错误。
这是我的实现:
class LinkedNode:
def __init__(self, val, nxt=None):
self.val = val
self.nxt = nxt
class LinkedList:
def __init__(self, head=None):
self.head = head
def append(self, new_val):
node = LinkedNode(new_val, None)
if self.head:
curr = self.head
while curr.nxt:
curr = curr.nxt
curr.nxt = node
else:
self.head = node
def print(self):
curr = self.head
while curr:
**print(curr.val)**
curr = curr.nxt
l1 = LinkedList()
l1.append(LinkedNode(2))
l1.append(LinkedNode(3))
l1.append(LinkedNode(4))
l1.print()
当打印功能中的 line 是“ print(curr.val)”时,该功能会打印内存地址。当线是“ print(curr.val.val)”时,该函数将打印2,3,4。
有人有可能的解决方案吗?
I am creating a Linked List implementation and I cannot fix this error of having to double call node.val.val
to print the data instead of the memory address.
Here is my implementation:
class LinkedNode:
def __init__(self, val, nxt=None):
self.val = val
self.nxt = nxt
class LinkedList:
def __init__(self, head=None):
self.head = head
def append(self, new_val):
node = LinkedNode(new_val, None)
if self.head:
curr = self.head
while curr.nxt:
curr = curr.nxt
curr.nxt = node
else:
self.head = node
def print(self):
curr = self.head
while curr:
**print(curr.val)**
curr = curr.nxt
l1 = LinkedList()
l1.append(LinkedNode(2))
l1.append(LinkedNode(3))
l1.append(LinkedNode(4))
l1.print()
When the line in the print function is "print(curr.val)", the function prints memory addresses. When the line is "print(curr.val.val)", the function prints 2,3,4.
Does anyone have a possible solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在将
linkedNode()
对象作为参数传递给.append()
函数:You were passing a
LinkedNode()
object as an argument to.append()
function:因为在这些行中,您正在创建
linkedNode
对象而不是值!之后,您在
Append
函数的范围内创建了一个新的linkedNode(linkedNode(2),无)
。将其更改为:
Because in these lines you are creating
LinkedNode
objects not values!After that, you created a new
LinkedNode(LinkedNode(2), None)
within the scope of theappend
function.Change it to: