python linkedlist,LinkedList在python中的实现

我正在用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)。在

谁能给我一个合适的逻辑来优化代码和降低复杂度。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值