gpt4 book ai didi

python - DoubleLinkedList 获取内存位置而不是节点值 - Python

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:39:23 25 4
gpt4 key购买 nike

我正在尝试创建一个双向链表,但我得到的是内存位置而不是节点值。感谢帮助

#!/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

关于python - DoubleLinkedList 获取内存位置而不是节点值 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53399981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com