Python编写双链表类,实现双链表的基本操作
时间: 2024-03-04 17:45:38 浏览: 84
以下是一个Python编写的双链表类,实现了双链表的基本操作:
```python
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
new_node.prev = current
def prepend(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
def insert_after_node(self, prev_node, data):
if not prev_node:
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
new_node.prev = prev_node
if new_node.next:
new_node.next.prev = new_node
def delete(self, data):
current = self.head
while current:
if current.data == data:
if current.prev:
current.prev.next = current.next
else:
self.head = current.next
if current.next:
current.next.prev = current.prev
return
current = current.next
def display(self):
current = self.head
while current:
print(current.data, end=" ")
current = current.next
print()
# 创建一个双链表对象
dllist = DoublyLinkedList()
# 在双链表末尾添加元素
dllist.append(1)
dllist.append(2)
dllist.append(3)
# 在双链表开头添加元素
dllist.prepend(0)
# 在指定节点后插入元素
dllist.insert_after_node(dllist.head.next, 1.5)
# 删除指定元素
dllist.delete(2)
# 打印双链表
dllist.display()
```
这个双链表类包含了以下基本操作:
1. `append(data)`: 在双链表末尾添加元素。
2. `prepend(data)`: 在双链表开头添加元素。
3. `insert_after_node(prev_node, data)`: 在指定节点后插入元素。
4. `delete(data)`: 删除指定元素。
5. `display()`: 打印双链表。
阅读全文