thinking:头节点 尾节点 边界条件
使用临时节点 存放数据 改变指针
遍历
class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class Linkedlist(object):
'''
[root]-[node0]-[node1]
'''
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = Node()
self.tailnode = None
self.length = 0
def __len__(self):
return self.length
def append(self, value):
if self.maxsize is not None and len(self) > self.maxsize:
raise Exception('linkedList is Full')
node = Node(value)
tailndoe = self.tailnode
if tailndoe is None:
self.root.next = node
else:
tailndoe.next = node
self.tailnode = node
self.length += 1
def iter_node(self):
curnode = self.root.next
while curnode is not self.tailnode:
yield curnode
curnode = curnode.next
if curnode is not None:
yield curnode
def __iter__(self):
for node in self.iter_node():
yield node.value
def remove(self, value):
''' 删除包含值的一个节点,将其前一个节点的next 指向下一个节点即可'''
prevnode = self.root
for curnode in self.iter_node():
if curnode.value == value:
prevnode.next = curnode.next
if curnode is self.tailnode:
self.tailnode = prevnode
del curnode
self.length -= 1
return 1 # 删除成功
else:
prevnode = curnode
return -1 # 删除失败
def find(self, value):
""" 查找一个节点,返回序号,从 0 开始
:param value:
"""
index = 0
for node in self.iter_node():
if node.value == value:
return index
def clear(self):
for node in self.iter_node():
del node
self.root.next = None
self.length = 0
self.tailnode = None
网友评论