Python 是否可以从单链表中获取索引值?
假设我生成了一个单链表,如下所示:Python 是否可以从单链表中获取索引值?,python,list,indexing,singly-linked-list,Python,List,Indexing,Singly Linked List,假设我生成了一个单链表,如下所示: # Singly Linked List class node: def __init__(self,data=None): self.data=data self.next=None class linked_list: def __init__(self): self.head=node() # Adds new node containing 'data' to the end of the linked list.
# Singly Linked List
class node:
def __init__(self,data=None):
self.data=data
self.next=None
class linked_list:
def __init__(self):
self.head=node()
# Adds new node containing 'data' to the end of the linked list.
def append(self,data):
new_node=node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=new_node
# Returns the length (integer) of the linked list.
def length(self):
cur=self.head
total=0
while cur.next!=None:
total+=1
cur=cur.next
return total
# Prints out the linked list in traditional Python list format.
def display(self):
elems=[]
cur_node=self.head
while cur_node.next!=None:
cur_node=cur_node.next
elems.append(cur_node.data)
print elems
# Returns the value of the node at 'index'.
def get(self,index):
if index>=self.length():
print "ERROR: 'Get' Index out of range!"
return None
cur_idx=0
cur_node=self.head
while True:
cur_node=cur_node.next
if cur_idx==index: return cur_node.data
cur_idx+=1
# Deletes the node at index 'index'.
def erase(self,index):
if index>=self.length():
print "ERROR: 'Erase' Index out of range!"
return
cur_idx=0
cur_node=self.head
while True:
last_node=cur_node
cur_node=cur_node.next
if cur_idx==index:
last_node.next=cur_node.next
return
cur_idx+=1
#Allows for bracket operator syntax (i.e. a[0] to return first item).
def __getitem__(self,index):
return self.get(index)
def getindex(self,data):
cur_node = self.data
while True:
cur_node = cur_node.next
if cur_node == data:
return cur_node.index
break
index +=1
假设我创建了一个单链表,如下所示:
new_list = linked_list()
new_list.append(5)
new_list.append(6)
new_list.append(8)
假设我想删除列表中的第二个值(索引1),它恰好是值6,但我不知道6的索引是什么。如何找到索引值6并使用它删除6?或者有没有其他方法可以在不知道索引值的情况下从单链表中删除值
编辑:我添加了一个名为getindex的新模块,该模块理论上应该在指定节点时获取索引,但我遇到了以下错误:
AttributeError:“非类型”对象没有属性“下一步”。它指的是cur_节点=cur_节点。getindex模块中的下一行。如何修复此错误?这是您需要的功能:
def getIndex(self,data):
cur_idx=0
cur_node=self.head
while cur_node.next:
cur_node=cur_node.next
if cur_node.data==data: return cur_idx
cur_idx+=1
return None
你是这样使用它的:
new_list = linked_list()
new_list.append(5)
new_list.append(6)
new_list.append(8)
new_list.display()
idx = new_list.getIndex(6)
if idx != None:
new_list.erase(idx)
new_list.display()
当调用.append()时,您可以向表示索引的节点添加属性。@Q.Holness我如何向节点添加属性以表示索引?在
get
函数中,您几乎准备好了它,而不是返回数据
返回索引
,而不是比较索引
比较数据
。根据链表理论,首选的方法是迭代所有元素,并在到达它时删除所需的元素。@scope我添加了另一个函数,但它似乎不起作用。有什么意见吗?