#coding:utf-8
class DoubleLinked:
def __init__(self):
self.DL = self.Node(None) # 哨兵
def insert(self, k):
self.pprint()
node = self.Node(k)
p = self.DL
temp = p.next
while temp and cmp(temp.k, k) == 1:
p = temp
temp = temp.next
node.pre = p
node.next = temp
p.next = node
if temp:
temp.pre = node
def search(self, k):
node = self.DL.next
while node and cmp(node.k, k) != 0:
node = node.next
return node
def remove(self,k):
self.pprint()
node = self.search(k)
if node:
node.pre.next = node.next
if node.next:
node.next.pre = node.pre
print 'delete %s ' % str(k)
else:
print 'not find %s ' % str(k)
def pprint(self):
node = self.DL
while node:
print '%s(%s %s %s)' % (str(id(node)), node.pre, str(node.k), node.next),
node = node.next
print
@classmethod
def test(cls):
DL = cls()
DL.insert(20)
DL.insert(18)
DL.insert(21)
DL.insert(19)
DL.remove(24)
DL.remove(21)
DL.remove(19)
DL.remove(18)
DL.remove(24)
DL.remove(20)
DL.remove(20)
DL.pprint()
print 'test over'
class Node:
def __init__(self, k):
self.pre = self.next = None
self.k = k
def __str__(self):
return str(id(self))
DoubleLinked.test()
双向链表
最新推荐文章于 2017-09-30 18:48:36 发布