思路
链表由节点组成,先规定节点(Node),包含data和指向下个节点的next
-
初始化
data当然就是传入的data了,next和prev指向None
-
添加
分两种情况:
- 链表为空,那么头节点和尾节点都指向新插入的节点
- 链表不为空,那么直接在尾部添加即可
-
遍历
因为只有链表的尾节点的next是指向None的,所以可以根据这点来从头遍历
-
删除某个节点
删除的时候分4种情况:
- 链表为空的时候
- 头节点,此时更改头节点的prev
- 尾节点,此时只需将尾节点的前一个节点(prev)的next指向None即可
- 中间的节点,修改要删除的节点的前驱和后继节点的next和prev指向就好
-
搜寻
遍历查找即可
-
清空链表
将头节点和尾节点都置为None即可
class Node:
def __init__(self,data=None, next=None, prev=None):
self.next = next
self.prev = prev
self.data = data
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def append(self,data):
'''添加元素'''
node = Node(data,None,None)
if self.head is None:
self.head = node
self.tail = self.head
else:
node.prev = self.tail
self.tail.next = node
self.tail = node
self.size += 1
def iter(self):
'''遍历链表'''
current = self.head
while current:
value = current.data
current = current.next
yield value
def delete(self,data):
'''根据数据删除节点'''
current = self.head
node_deleted = False
if current is None: #链表为空
node_deleted = False
elif current.data == data: #要删除的元素在链表的开头
self.head.prev = None
self.head = current.next
node_deleted = True
elif self.tail.data == data: #要删除的元素在链表的结尾
self.tail = self.tail.prev
self.tail.next = None
node_deleted = True
else: #要删除的元素在链表中间的某一处
while current:
if current.data == data:
current.prev.next = current.next
current.next.prev = current.prev
node_deleted = True
current = current.next
if node_deleted: #如果有元素被删除,长度就减一
self.size -= 1
def contain(self,data):
'''搜寻某个节点'''
for node in self.iter():
if data == node:
return True
return False
def clear(self):
'''清空链表'''
self.tail = None
self.head = None