Python 双向链表实现

# -*- 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值