使用pyhton语言写一个双向链表
时间: 2023-01-15 16:23:45 浏览: 137
双向链表实现
首先,我们需要定义一个节点类,包括数据域和两个指针域,一个向前指针和一个向后指针:
```python
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
```
然后我们再定义一个双向链表类,包括头指针、尾指针和节点数量,以及各种操作的方法:
```python
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def append(self, data):
"""在尾部添加节点"""
new_node = Node(data)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
self.count += 1
def delete(self, node):
"""删除节点"""
if self.head is None or node is None:
return
if self.head == node:
self.head = node.next
if self.tail == node:
self.tail = node.prev
if node.prev is not None:
node.prev.next = node.next
if node.next is not None:
node.next.prev = node.prev
self.count -= 1
def find(self, data):
"""查找节点"""
current = self.head
while current is not None:
if current.data == data:
return current
current = current.next
return None
def print_list(self):
"""打印链表"""
current = self.head
while current is not None:
print(current.data, end=' ')
current = current.next
print()
```
这样就可以使用双向链表了,例如:
```python
dl_list = DoublyLinkedList()
dl_list.append(1)
dl_list.append(2)
dl_list.append(3)
dl_list.append(4)
dl_list.print_list() # 输出 1 2 3 4
node = dl_list.find(3)
dl_list.delete(
阅读全文