'''
双向链表
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def __str__(self):
return str(self.data)
class DoubleList:
def __init__(self):
self._head = None
def isEmpty(self):
return self._head == None
def append(self, item):
# 尾部添加
node = Node(item)
if self.isEmpty():
self._head = node
else:
cur = self._head
while cur.next != None:
cur = cur.next
cur.next = node
# 求长度
def add(self, item):
node = Node(item)
if self.isEmpty():
self._head = node
else:
node.next = self._head
self._head.prev = node
self._head = node
def len(self):
cur = self._head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def print_all(self):
cur = self._head
while cur != None:
print(cur)
cur = cur.next
def insert(self, index, item):
if index < 0 or index >= self.len():
raise IndexError('index Error')
if index ==0:
node = Node(item)
node.next = self._head
self._head.prve = node
self._head = node
else:
node = Node(item)
cur = self._head
while index-1:
cur = cur.next
index-=1
if index == 0:
node.next = self._head
self._head = node
else:
cur = self._head
while index - 1:
cur = cur.next
index -= 1
# cur就是index 的前一个节点
# 设置弄得节点的前一个cur节点
node.prve = cur
# 设置node的后一个节点
node.next = cur.next
# 设置的是cur的next节点的prve直向node
cur.next.prev = node
# 设置cur的next节点就是node
cur.next = node
def remove(self, item):
if self.isEmpty():
raise ValueError('没有找到该元素')
else:
cur = self._head
if cur.data ==item:
#删除的是头的节点
if cur.next ==None:
#只有头节点
self._head = None
else:
#除了头部节点,还有其他的节点
cur.next.prev = None
self._head = cur.next
else:
while cur !=None:
if cur.data == item:
cur.prev.next = cur.next
cur.next.prev = cur.prev
break
cur = cur.next
def update(self, index, item):
pass
if __name__ == '__main__':
dlist = DoubleList()
print(dlist.len())
print(dlist.isEmpty())
# dlist.append(6)
# dlist.append(9)
# dlist.append(5)
# print(dlist.len())
# print(dlist.isEmpty())
# dlist.print_all()
dlist.add(6)
dlist.add(9)
dlist.add(5)
dlist.insert(2,55)
# dlist.remove(55)
dlist.print_all()
dlist.remove(6)
dlist.print_all()
双向链表
于 2019-08-20 16:32:09 首次发布