# -*- coding:utf-8 -*- import time class WarpLinkNode(object): # 双链表节点包裹类 def __init__(self, real_item): self.data = real_item self.prev = None self.next = None def __eq__(self, other): # 实现节点相等判断 if other.data == self.data: return True return False class LinkList(object): def __init__(self): self.head = None self.tail = None def get_head(self): if self.head: return self.head.data def get_tail(self): if self.tail: return self.tail.data def append(self, item): curr = self.tail if curr: curr.next = WarpLinkNode(item) curr.next.prev = curr self.tail = curr.next else: self.head = WarpLinkNode(item) self.tail = self.head def remove(self, item): wrapItem = WarpLinkNode(item) curr = self.head while curr: if curr == wrapItem: if curr.prev: if curr is self.tail: curr.prev.next = None self.tail = curr.prev else: curr.prev.next = curr.next curr.next.prev = curr.prev else: if curr is self.tail: self.tail = None self.head = None else: self.head = curr.next self.head.prev = None break curr = curr.next def __str__(self): curr = self.head ret = [] while curr: ret.append(curr.data.__str__()) curr = curr.next return "<->".join(ret) if __name__ == "__main__": ll = LinkList() ll.append(1) ll.append(2) ll.append(3) ll.append(4) print ll print "----------------" ll.remove(3) print ll print ll.get_head() print ll.get_tail() print "----------------" ll.remove(4) print ll print ll.get_head() print ll.get_tail() print "----------------" ll.remove(1) print ll print ll.get_head() print ll.get_tail() t1 = time.clock() l = LinkList() for i in xrange(100000): l.append(i) for i in xrange(100000): l.remove(i) print l.__dict__ print time.clock() - t1 t1 = time.clock() p_l = [] for i in xrange(100000): p_l.append(i) for i in xrange(100000): p_l.remove(i) print time.clock() - t1
Python 双向链表实现
最新推荐文章于 2021-02-23 22:51:17 发布