[英]How to select the first node in linked list?
我想 select 鏈表中的第一個節點並呈現所選節點。 這是我創建的全部代碼。 “前置”在第一個節點之前添加節點。 “追加”在鏈表的最后一個之后添加節點。
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()
返回一個節點 object。 它的data
是字符串'Jodie'
,並且由於您定義了它的__str__
方法,當您打印節點時,您將看到該字符串。 但是節點本身是一個節點,而不是一個字符串。
如果您比較data
屬性:
print(names.pop_start().data == "Jody")
...你會得到True
,如預期的那樣。 但無論如何, pop_start
只返回數據可能更有意義,而不是節點 object。 您可以這樣做:
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.