[英]How to select the first node in linked list?
I want to select the first node in the linked list and present the selected node.我想 select 链表中的第一个节点并呈现所选节点。 This is the whole code that I've created.
这是我创建的全部代码。 The "prepend" adds the node before the first node.
“前置”在第一个节点之前添加节点。 The "append" adds the node after the last of the linked list.
“追加”在链表的最后一个之后添加节点。
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())
I can get the result of Jody
.我可以得到
Jody
的结果。 But if instead, I test for但如果相反,我测试
print(names.pop_start() == "Jody")
It shows False
.它显示
False
。 What is the reason?是什么原因?
names.pop_start()
returns a Node object. names.pop_start()
返回一个节点 object。 Its data
is the string 'Jodie'
, and because of how you've defined its __str__
method, when you print the node, the string is what you'll see.它的
data
是字符串'Jodie'
,并且由于您定义了它的__str__
方法,当您打印节点时,您将看到该字符串。 But the node itself is a node, not a string.但是节点本身是一个节点,而不是一个字符串。
If you compare to the data
attribute:如果您比较
data
属性:
print(names.pop_start().data == "Jody")
...you'll get True
, as intended. ...你会得到
True
,如预期的那样。 But it would probably make more sense for pop_start
to just return the data anyway, rather than the Node object.但无论如何,
pop_start
只返回数据可能更有意义,而不是节点 object。 Here's how you could do that:您可以这样做:
def pop_start(self):
if self.head is None:
return None
else:
data = self.head.data
if self.head is self.tail:
self.tail = None
self.head = self.head.next
return data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.