数据结构双向链表的创建代码
时间: 2024-11-13 18:24:23 浏览: 3
双向链表是一种特殊的数据结构,每个节点包含两个指针,一个指向前一个节点,另一个指向后一个节点。这里是一个简单的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 insert_at_beginning(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 insert_at_end(self, data):
new_node = Node(data)
if self.head is not None:
current = self.head
while current.next:
current = current.next
current.next = new_node
new_node.prev = current
# 删除指定节点
def delete_node(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
# 示例使用
dll = DoublyLinkedList()
dll.insert_at_beginning(1)
dll.insert_at_end(3)
```
阅读全文