私はリンクリストをpythonで作成するプロジェクトを持っています。組み込み関数を使わないリンクリストの作成
私のプログラムは、リストに追加し、そこから削除して要素を取得する必要があります。簡単に聞こえますか?違う! print
、str
...)
私のコードには1つの問題があります。空のリストを初期化して要素を追加する必要がありますが、 1で1。他のすべては正常に動作します。
私の質問:
が、これは通常のPythonリストがどのように動作するかですか?
ループでリンクリストに項目を追加することはできますか? (別のリストなし)
は、ここでは、コードです:
class Node: # the node class
def __init__(self, cargo = None, next = None): # __init__ stands for initialize
self.cargo = cargo # e.g. steve
self.next = next # represents the next node or None if its the last
def __str__(self): # __str__ is called when the node is printed or converted to a string
return str(self.cargo) # return a string
class List: # the main list class
def __init__(self): # default is to initialize an empty list
self.first_node = None
self.last_node = None
self.length = 0
def get(self, position, length): # function for efficiency
if position == "end":
position = length - 1 # last
if position > length - 1: # can't go beyond last
raise ValueError("List index out of range")
prv_node = self.first_node
node = self.first_node # start at the first
num = 0
while num < position: # go up to position
prv_node = node # remember the previous node
node = node.next # next node!
num = num + 1
return prv_node, node, position
def add_node(self, cargo, position = "end"): # adds a node
prv_node, node, position = self.get(position, self.length + 1) # +1 because the length is being increased
print("adding node at "+str(position)+": "+str(cargo))
if position == 0: # first
self.first_node = Node(cargo, next = self.first_node) # the first node is the new node
if self.length == 0: # first node to be added
self.last_node = self.first_node # there is only one node
elif position == self.length: # last
self.last_node.next = Node(cargo, next = None) # last_node.next was None, it is now a new node
self.last_node = self.last_node.next # last node is now the new last node
else: # normal
prv_node.next = Node(cargo, next = node) # stick it in between
self.length = self.length + 1 # length is now + 1
def get_node(self, position): # gets a node
...
def remove_node(self, position): # removes a node
...
def __str__(self): # when the list is printed
node = self.first_node # start from the first
string = ""
while node != self.last_node: # go to the end
string = string + str(node) + ", " # print each node
node = node.next
string = string + str(self.last_node) # last node hasn't been added yet
return string
# initialize
mylist = List()
mylist.add_node("steve")
mylist.add_node("james")
mylist.add_node("tom")
mylist.add_node("david")
mylist.add_node("hoe-yin")
mylist.add_node("daniel")
print(mylist)
[EDIT] 2番目の質問の再言い回し
あなたの2番目の質問はどういう意味ですか? – MooingRawr
"*これは普通のpythonリストがどのように動作するのか*" - そうかもしれない、そうでないかもしれない。言語は* how *リストが実装されていることを指定するのではなく、必要な機能のみを指定します。 Cの実装では、PythonオブジェクトへのポインタのC配列を使用していますが、オブジェクト自体にはリンクが含まれていないので、その場合はnoです。 – cdarke
"ループでリンクリストを初期化することはできますか?" ?ループ内のリストに項目を追加する方法があるかどうかを知りたいですか? – Nf4r