defremove(self, olddata): """从单链表中删除所有的olddata""" cur = self.head pre = None while cur isnotNone: if cur.item == olddata: ifnot pre: self.head = cur.next else: pre.next = cur.next cur = cur.next else: pre = cur cur = cur.next
deflength(self): """返回单链表的长度""" cur = self.head count = 0 while cur isnotNone: count += 1 cur = cur.next return count
deftravel(self): """打印整个单链表 return ------ ls: list,从前至后的单链表""" cur = self.head ls = [] while cur isnotNone: ls.append(cur.item) cur = cur.next return ls
defsearch(self, data): cur = self.head while cur isnotNone: if cur.item == data: returnTrue else: cur = cur.next returnFalse
defadd(self, newdata): """将新节点添加到单向循环链表头部。即头指针指向新节点,尾节点的指针指向新节点,新节点的指针指向原头节点""" node = SingleListNode(newdata) if self.is_empty(): self.head = node node.next = node else: cur = self.head while cur.next != self.head: cur = cur.next node.next = self.head cur.next = node self.head = node
defappend(self, newdata): """与add方法唯一的区别为链表头的指针不变""" node = SingleListNode(newdata) if self.is_empty(): self.head = node node.next = node else: cur = self.head while cur.next != self.head: cur = cur.next node.next = self.head cur.next = node
defremove(self, olddata): """删除一个指定的节点""" cur = self.head pre = None if self.is_empty(): return elif self.head.item == olddata: while cur.next != self.head: cur = cur.next cur.next = self.head.next self.head = self.head.next else: pre = self.head while cur.next != self.head: if cur.item == olddata: pre.next = cur.next return pre = cur cur = cur.next if cur.item == olddata: pre.next = self.head
deflength(self): if self.is_empty(): return0 cur = self.head count = 1 while cur.next != self.head: count += 1 cur = cur.next return count
deftravel(self): if self.is_empty(): return cur = self.head ls = [] while cur.next != self.head: ls.append(cur.item) cur = cur.next ls.append(cur.item) return ls
defsearch(self, data): if self.is_empty(): returnFalse cur = self.head while cur.next != self.head: if cur.item == data: returnTrue else: cur = cur.next if cur.item == data: returnTrue returnFalse
defappend(self, newdata): node = DoubleListNode(newdata) if self.is_empty(): self.head = node else: cur = self.head while cur.nextisnotNone: cur = cur.next cur.next = node node.prev = cur
definsert(self, pos, newdata): if pos <= 0: self.add(newdata) elif pos > self.length() - 1: self.append(newdata) else: node = DoubleListNode(newdata) cur = self.head count = 0 while count < pos - 1: count += 1 cur = cur.next node.next = cur.next node.prev = cur cur.next.prev = node cur.next = node
defremove(self, olddata): """删除一个指定的节点""" if self.is_empty(): return elif self.head.item == olddata: if self.head.nextisNone: self.head = None else: self.head.next.prev = None self.head = self.head.next else: cur = self.head while cur.nextisnotNone: if cur.item == olddata: cur.next.prev = cur.prev cur.prev.next = cur.next return cur = cur.next if cur.item == olddata: cur.prev.next = None