假设我有一个单链表生成为:
# 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:'NoneType'对象没有属性'next'。它指的是getindex模块中的cur_node = cur_node.next行。如何解决此错误?
答案 0 :(得分:-1)
这是您需要的功能:
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()