#构造节点类 class Node(object): def __init__(self,data=None,_next=None): ''' self.data:为自定义的数据 self.next:下一个节点的地址(这里为下一个数据建立了一个对象) ''' self.data = data self.next = _next def __repr__(self): return str(self.data) #单链表 class MyChain(object): def __init__(self): '''初始化空链表''' self.head=None self.length=0 def __repr__(self): """ 重构:对链表进行输出 """ temp = self.head cstr = "" for i in range(self.length-1): cstr += str(temp.data)+' -> ' temp = temp.next cstr += str(temp.data) return cstr def isEmpty(self): return (self.length==0) def append(self, mydata): '''增加节点''' item=None if isinstance(mydata, Node): item=mydata else: item=Node(mydata) if not self.head: self.head=item self.length +=1 else: node=self.head while node.next: node=node.next node.next=item self.length += 1 def delete(self,index): if self.isEmpty(): print("this chain table is empty") return if index<0 or self.length<=index: print("index is out of range") return if index==0: self.head=self.head.next self.length -=1 return #prev为保存前导节点 #node为保存当前节点 #当j与index相等时就 #相当于找到要删除的节点 j=0 node=self.head prev=self.head while node.next and j < index: prev = node node = node.next j += 1 if j == index: prev.next = node.next self.length -= 1 def update(self, index, data): '''修改节点''' if self.isEmpty() or index < 0 or index >= self.length: print('error: out of index') return j = 0 node = self.head while node.next and j < index: node = node.next j += 1 if j == index: node.data = data def getItem(self, index): '''查找节点''' if self.isEmpty() or index < 0 or index >= self.length: print("error: out of index") return j = 0 node = self.head while node.next and j < index: node = node.next j += 1 return node.data def getIndex(self, data): j = 0 if self.isEmpty(): print("this chain table is empty") return node = self.head while node: if node.data == data: print("index is %s"%str(j)) return j node = node.next j += 1 if j == self.length: print ("%s not found" % str(data)) return def insert(self, index, mydata): if self.isEmpty(): print ("this chain tabale is empty") return if index < 0 or index >= self.length: print ("error: out of index") return item = None if isinstance(mydata, Node): item = mydata else: item = Node(mydata) if index == 0: item.next = self.head self.head = item self.length += 1 return j = 0 node = self.head prev = self.head while node.next and j < index: prev = node node = node.next j += 1 if j == index: item.next = node prev.next = item self.length += 1 def clear(self): self.head = None self.length = 0 if __name__=="__main__": L = [1,2,3,4,5,6,7,8,9,0] chain = MyChain() for i in L: n = Node(i) chain.append(n) chain.getIndex(2) chain.insert(0, 0) chain.getItem(9) chain.update(3, 77) print(chain)