经过几天的单链表学习,积累了很多单链表节点类的方法和属性,见以下代码。今天对其中的属性 values 做些修改,就能得到对应的生成器方法和属性。特别是当链表很长时,生成器比列表更节省内存空间。
class Node():
def __init__(self, value=None, Next=None):
self.val = value
self.next = Next
if type(self.next)==Node and self.next.val==None:
self.next=None
def __repr__(self):
return f'Node({self.val}->{self.next})'
def __str__(self):
return f'{self.val}->{self.next}'
def __len__(self):
if self.val is None:
return 0
length,ptr = 0,self
while ptr is not None:
length += 1
ptr = ptr.next
return length
def __eq__(self, other):
ptr1,ptr2 = self,other
if len(ptr1)!=len(ptr2):
return False
while ptr1 is not None:
if ptr1.val!=ptr2.val:
return False
ptr1 = ptr1.next
ptr2 = ptr2.next
else:
return True
def size(self):
return self.__len__()
@property
def length(self):
return self.size()
@property
def value(self):
return self.val
@property
def values(self):
ret,ptr = [],self
while ptr is not None:
ret.append(ptr.val)
ptr = ptr.next
return ret
def pprint(self):
items = [str(i) for i in self.values]
if items==[]:
print('None->None')
elif len(items)==1:
print(f'{items[0]}->None')
else:
print('->'.join(items)+'->None')
def isNode(node):
return isinstance(node,Node) and isinstance(node.next,(Node,type(None)))
def build(*data, split=True):
'''把数据转换成节点链表'''
lst,ret = [],Node()
for val in data:
if type(val) is str:
if not split:
lst.append(val)
continue
if str=='':
continue
try:
num = int(val)
lst.extend([int(_) for _ in val])
except:
lst.extend([_ for _ in val])
elif hasattr(val,'__iter__'):
lst.extend([_ for _ in val])
elif type(val) is Node:
if not val.isNone:
lst.extend(val.values)
else:
lst.append(val)
ret = Node()
for i in lst[::-1]:
ret = Node(i, ret)
return ret
def copy(node):
ret = Node()
ptr1,ptr2 = node,ret
while ptr1 is not None:
ptr2.next = Node(ptr1.val)
ptr1,ptr2 = ptr1.next,ptr2.next
return ret.next
增加链表节点数据域的遍历生成器(方法、属性):
def items(self):
ptr = self
while ptr is not None:
yield ptr.val
ptr = ptr.next
@property
def generator(self):
yield from self.values
yield 语法糖: yield form?iterable object? (python 3.3+)
等价于: for item in iterable: ????????yield?item
|