我沒有看到這個帖子here【JAVA]和在嘗試類似的解決方案,但指出線程沒有完全回答我的問題)在Python中的單向鏈表中的另一個節點之前插入一個節點?
我需要用單鏈表的工作,想嘗試和執行的insertBefore( ) 方法。我知道雙鏈表有一個先前的屬性,而單鏈表沒有,所以我明白這可能會更好地使用雙鏈表完成,但這是作業的要求,我試圖解決的事情。
到目前爲止:我有我的Node類設置以及我的SinglyLinkedList類。我也有我的insertBefore()方法,這是我的目標,我陷入困境。
您會在我的if語句中看到我希望將node.next.value
與我的targetNode
(請注意targetNode是一個值)進行比較 - 爲什麼我的node.next.value向我拋出以下錯誤? if node.next.value == targetNode: AttributeError: 'NoneType' object has no attribute 'value'
# this is our node object
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
# this is our singly linked list object
class SinglyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def insertBefore(self, targetNode, value):
# create new node
newNode = Node(value)
# find target node to insert
node = self.head
if node == None:
print 'There aren\'t any nodes to insert before!'
else:
found = None
# search nodes
while node:
if node.next.value == targetNode:
found = True
print node.value + ' <--this was node before target'
beforeInsert = node
afterInsert = node.next
beforeInsert.next = newNode
newNode.next = afterInsert # sets new node's next to target node
node = node.next # continues through while loop
else:
node = node.next
if found != True:
print 'Your target node of {} was not found in the list!'.format(targetNode)
請注意:我能得到這個爲insertAfter()方法(不包括在上面的代碼段)工作,但我在努力的node.next
與targetNode
對象相匹配。
爲什麼有人投我這個問題?我上面的問題出了什麼問題,爲什麼我不能問這樣的問題? – natureminded