1 Star 0 Fork 0

erickhuang/Python3_Practice

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Linklist.py 1.91 KB
一键复制 编辑 原始数据 按行查看 历史
erickhuang 提交于 2017-07-02 22:18 . Finished Linklist.py
'''
实现一个单向链表
'''
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)))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/erickhuang/Python3_Practice.git
git@gitee.com:erickhuang/Python3_Practice.git
erickhuang
Python3_Practice
Python3_Practice
master

搜索帮助