私は[javaの]この投稿hereを見やったと同様のソリューションをしようとしていますが、注意スレッドは完全に私の質問に答えなかった)別のノードの前にノードをPythonの単独リンクリストに挿入しますか?
私は単独リンクリストと協力し、(のinsertBeforeを試してみて、実行したいする必要があります) 方法。私は二重リンクリストは以前の属性を持っていると理解していますが、一重リンクリストはそうではありませんので、これは二重リンクリストを使ってよりうまくいくかもしれませんが、これは課題の要件であり、
これまでのところ、私のNodeクラスのセットアップは私のSinglyLinkedListクラスと一緒になっています。私はまた、私の目標であり、私が立ち往生している私のinsertBefore()メソッドを持っています。
node.next.value
と私のtargetNode
を比較したいと思います(targetNodeは値です)。なぜ、node.next.valueが私に次のエラーを投げかけていますか?私はこれが(上記のスニペットには含まれません)insertAfter()メソッドのために働くことを得ることができたが、targetNode
オブジェクトにnode.next
を一致させるのに苦労しています: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)
に注意してください。
なぜこの質問をしたのですか?上記の質問に何が問題なのですが、なぜこのようなことを聞かないのですか? – natureminded