class Node(object):
def __init__(self,elem):
self.elem = elem
self.next = None
self.prev = None
class DoubleLinkList(object):
"""双向链表"""
def __init__(self, node = None):
#node = None为默认参数
self.__head = node
def is_empty(self):
return self.__head is None
def length(self):
cur = self.__head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
cur = self.__head
while cur is not None:
print(cur.elem, end=" ")
cur = cur.next
print()
return
def add(self,item):
node = Node(item)
node.next = self.__head
self.__head = node
node.next.prev = node
def append(self,item):
node = Node(item)
if self.is_empty():
self.__head = node
node.prev = self.__head
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
node.prev = cur
def insert(self,pos,item):
node = Node(item)
cur = self.__head
if pos <= 0:
self.add(item)
elif pos > self.length() - 1:
self.append(item)
else:
count = 0
while count < pos:
count += 1
cur = cur.next
#遍历完后指向要插入的位置
node.next = cur
node.prev = cur.prev
cur.prev.next = node
cur.prev = node
def search(self,item):
cur = self.__head
while cur != None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
def remove(self,item):
cur = self.__head
pre = None
while cur != None:
if cur.elem == item:
if cur == self.__head:
self.__head = cur.next
if cur.next:
cur.next.prev = None
else:
cur.prev.next = cur.next
if cur.next:
cur.next.prev = cur.prev
break
else:
pre = cur
cur = cur.next
if __name__ == '__main__':
sll = DoubleLinkList()
print(sll.is_empty())
print(sll.length())
sll.append(1)
print(sll.is_empty())
print(sll.length())
sll.append(2)
sll.append(3)
sll.add(100)
sll.append(4)
sll.append(5)
sll.insert(-1,50)
sll.append(6)
sll.append(6)
sll.insert(10,33)
sll.insert(5,"x")
sll.travel()
print(sll.length())
print(sll.search(3))
print(sll.search(101))
sll.remove(100)
sll.travel()
sll.remove(50)
sll.travel()
sll.remove(33)
sll.travel()
运行结果:
True
0
False
1
50 100 1 2 3 x 4 5 6 6 33
11
True
False
50 1 2 3 x 4 5 6 6 33
1 2 3 x 4 5 6 6 33
1 2 3 x 4 5 6 6