线性表的链式存储结构代码
时间: 2024-10-25 11:02:13 浏览: 20
线性表的链式存储结构是一种数据结构,它将元素通过链接连接起来,每个节点包含数据域和指针域。以下是使用Python创建一个简单单链表的代码示例:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 插入节点到链表头部
def insert_at_start(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# 插入节点到链表尾部
def append(self, data):
if not self.head:
self.head = Node(data)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(data)
# 删除指定值的节点
def delete(self, key):
if self.head and self.head.data == key:
self.head = self.head.next
else:
current = self.head
prev = None
while current and current.data != key:
prev = current
current = current.next
if current:
prev.next = current.next
# 打印链表
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print("Elements in the linked list:", elements)
# 示例
linked_list = LinkedList()
linked_list.insert_at_start(5)
linked_list.append(10)
linked_list.delete(5)
linked_list.display()
```
阅读全文