代码拉取完成,页面将自动刷新
'''
实现一个单向链表
'''
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Linklist:
def __init__(self):
self.head = None
self.length = 0
def __len__(self):
return self.length
def __str__(self):
return 'single link list'
def __iter__(self):
self.start = self.head
return self
def __next__(self):
if self.start == None:
raise StopIteration
ret = self.start.data
self.start = self.start.next
return ret
def __setitem__(self, i, node):
if i > self.length:
return
if i == 0:
node.next = self.head
self.head = node
return
pre = self.get_pre_node(i)
node.next = pre.next
pre.next = node
return
def __delitem__(self, i):
if i + 1 > self.length:
return
if i == 0:
self.head = self.head.next
return
pre = self.get_pre_node(i)
pre.next = pre.next.next
def __getitem__(self, i):
if i+1 > self.length:
return None
ret = self.head
while i != 0:
ret = ret.next
i -= 1
return ret
def append(self, node, tohead=True):
self.length += 1
if self.head == None:
self.head = node
return self.length
if tohead:
node.next = self.head
self.head = node
return self.length
last = self.get_last()
last.next = node
return self.length
def sort(self):
pass
def get_last(self):
pre, temp = None, self.head
while temp != None:
pre = temp
temp = temp.next
return pre
def get_pre_node(self, i):
if i > self.length:
return None
pre, temp = None, self.head
while i != 0 and temp != None:
pre = temp
temp = temp.next
i -= 1
return pre
if __name__ == '__main__':
print('testing...')
mylist = Linklist()
mylist.append(Node(0), False)
mylist.append(Node(1), False)
mylist.append(Node(2), False)
mylist.append(Node(3), False)
for x in mylist:
print(x)
print('len = {}'.format(len(mylist)))
mylist[5] = Node('erick')
for x in mylist:
print(x)
print('len = {}'.format(len(mylist)))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。