双向链表的Python代码
时间: 2024-06-19 17:01:27 浏览: 102
双向链表(Doubly Linked List)是一种数据结构,其中每个节点都有两个指针,分别指向前一个节点和后一个节点。在Python中,我们可以这样实现一个简单的双向链表:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
# 插入节点到链表头部
def insert_at_start(self, data):
new_node = Node(data)
if self.head is not None:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
# 在链表尾部插入节点
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
new_node.prev = last_node
# 删除指定节点
def delete(self, key):
current = self.head
if current and current.data == key:
self.head = current.next
if self.head:
self.head.prev = None
return
prev = None
while current and current.data != key:
prev = current
current = current.next
if current is None:
return
prev.next = current.next
if current.next:
current.next.prev = prev
# 遍历链表并打印节点值
def print_list(self):
current = self.head
while current:
print(current.data, end=" <-> ")
current = current.next
print("None")
# 示例用法
dll = DoublyLinkedList()
dll.insert_at_start(1)
dll.insert_at_start(2)
dll.append(3)
dll.print_list() # 输出: 2 <-> 1 <-> 3 <-> None
```
阅读全文