我正在用python(3.7.4)实现LinkedList,模块代码如下:
在LinkedList.py在class Node:
def __init__(self,value):
self.value = value
self.ref = None
class LinkedList(Node):
def __init__(self):
self.__head = None
self.__cur = None
self.__count = 0
def add(self,value):
if self.__head is None:
self.__cur = Node(value)
self.__head = self.__cur
else:
self.__cur.ref = Node(value)
self.__cur = self.__cur.ref
self.__count += 1
def getList(self):
temp = self.__head
while temp!=None:
yield temp.value
temp = temp.ref
def delete(self,value):
temp = self.__head
while temp!=None:
if temp.value == value and temp == self.__head:
self.__head = temp.ref
del temp
self.__count -= 1
break
elif temp.ref != None and temp.ref.value == value:
temp_ref = temp.ref.ref
del temp.ref
self.__count -= 1
temp.ref = temp_ref
break
temp = temp.ref
def __getitem__(self,index):
i = 0
temp = self.__head
if type(index) is int:
while temp!=None:
if i == index:
return temp.value
temp = temp.ref
i += 1
elif type(index) is slice:
if index.start is None:
start = 0
else: start = index.start
if index.stop is None:
stop = self.__count
else: stop = index.stop
if index.step is None:
step = 1
else: step = index.step
returningList = list()
while temp!=None:
if start <= i < stop:
returningList.append(temp.value)
if i==0:
i = start
for _ in range(start):
if temp != None:
temp = temp.ref
else:
i+=step
for _ in range(step):
if temp != None:
temp = temp.ref
return returningList
def __len__(self):
return self.__count
以上功能均正常工作,本模块无任何错误。在
但我的问题是__getitem__()方法。我无法得出确切的逻辑,它变得太大了。在
它也不适用于负指数,比如obj[-1]什么都不返回(len(obj)在这里不是0)。在
谁能给我一个合适的逻辑来优化代码和降低复杂度。在