class Node(object):
def __init__(self,item):
self.item = item
self.next = None
self.prev = None
class DLinkList(object):
def __init__(self):
self.__head = None
#判断空列表
def is_empty(self):
return self.__head is None
#长度
def length(self):
cur = self.__head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
#遍历
def travel(self):
cur = self.__head
while cur != None:
print(cur.item,end="")
cur = cur.next
print("")
#插入头部
def add(self,item):
node = Node(item)
cur = self.__head
if self.is_empty():
self.__head = node
else:
node.next = self.__head
node.next.prev = node
self.__head = node
#插入尾部
def append(self,item):
node = Node(item)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
node.prev = cur
#查找
def search(self,item):
cur = self.__head
while cur != None:
if cur.item == item:
return True
cur = cur.next
else:
return False
#指定位置插入
def insert(self,pos,item):
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = Node(item)
cur = self.__head
count = 0
while count < (pos-1):
count += 1
cur = cur.next
node.next = cur.next
node.next.prev = node
node.prev = cur
cur.next = node
#删除
def remove(self,item):
if self.is_empty():
return
else:
cur = self.__head
#首个元素就是需要被删除的元素
if cur.item == item:
#如果只有一个节点
if cur.next == None:
self.__head = None
else:
cur.next.prev = None
self.__head = cur.next
return
while cur != None:
if cur.item == item:
cur.next.prev = cur.prev
cur.prev.next = cur.next
break
cur = cur.next
if __name__ == '__main__':
ll = DLinkList()
ll.add(1)
ll.add(2)
ll.append(3)
ll.insert(2, 4)
ll.insert(4, 5)
ll.insert(0, 6)
print("length:", ll.length())
ll.travel()
print(ll.search(3))
print(ll.search(4))
ll.remove(1)
print("length:", ll.length())
ll.travel()
运行结果:
length: 6
621435
True
True
length: 5
62435