Python 如何选择链表中的第一个节点?
我要选择链接列表中的第一个节点并显示选定的节点。这就是我创建的全部代码。“prepend”将节点添加到第一个节点之前。“追加”将节点添加到链接列表的最后一个节点之后Python 如何选择链表中的第一个节点?,python,Python,我要选择链接列表中的第一个节点并显示选定的节点。这就是我创建的全部代码。“prepend”将节点添加到第一个节点之前。“追加”将节点添加到链接列表的最后一个节点之后 class Node: def __init__(self, data=None, next=None): self.data = data self.next = next def __str__(self): return str(self.data)
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
# LinkedList definition here
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def prepend(self, data):
node = Node(data, self.head)
if self.head is None:
self.head = node
self.tail = node
else:
node.next = self.head
self.head = node
def append(self, data):
node = Node(data, None)
if self.tail is None:
# No elements in list
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def pop_start(self):
if self.head is None:
return None
if self.head.next is None:
cur = self.head
self.head = None
return cur
else:
if self.head != None:
temp = self.head
self.head = self.head.next
return temp
names = LinkedList()
names.append("Bill Gates")
names.append("Steve Jobs")
names.prepend("Jody")
print(names.pop_start())
我可以得到Jody的结果。但如果相反,我测试
print(names.pop_start() == "Jody")
它显示False
。原因是什么?names.pop_start()
返回一个节点对象。它的数据
是字符串'Jodie'
,由于您定义了它的\uuuu str\uuuu
方法,当您打印节点时,您将看到字符串。但是节点本身是一个节点,而不是一个字符串
如果与数据
属性进行比较:
print(names.pop_start().data==“Jody”)
…您将按预期获得True
。但是如果pop_start
只是返回数据,而不是返回节点对象,可能会更有意义。以下是您可以做到这一点的方法:
def pop_启动(自):
如果self.head为无:
一无所获
其他:
数据=self.head.data
如果self.head是self.tail:
self.tail=None
self.head=self.head.next
返回数据
您的代码不完整,但在调用pop\u start
时修改了对象,因此如果打印两次,第二次pop将为您提供不同的值。你还返回一个链表节点,它不等于一个字符串,不管你对print(names.pop_start()=“Jody”)的测试代码是什么意思,它可能返回另一个值?我发布了我的全部代码。如果我将节点更改为字符串,print(names.pop_start()=“Jody”)是否为真?@JodyHou如果我理解正确,是的,这也应该行得通。我已经编辑了我的答案。