Python实现链表
1.1实现单向链表
#链表结构分成2部分 head,tail #('a',('b',('c',none))) #迭代时候 Head is a ;;;; tail is ('b',('c',none)) #append时候 tail指向最后一个节点(c,'none) class Node: def __init__(self,item,next=None): self.item = item self.next = next def __repr__(self): return repr(self.item) class SingleLinked: def __init__(self): self.head = None self.tail = None self.items = [] def append(self,item): node = Node(item) if self.head is None: self.head = node else: self.tail.next = node self.tail = node self.items.append(node) return self def iternode(self): while self.head: yield self.head self.head = self.head.next def __getitem__(self, item): return self.items[item] ll = SingleLinked() ll.append(1).append(2).append(3).append(4) print(ll[2]) for i in ll.iternode(): print(i)
本文为原创文章,转载请标明出处