基于带头结点的链式存储结构,编写程序,实现下述功能: 初始化一个空链表 链表的置空和销毁 实现元素的查找、插入和删除 输出链表的全部元素 链表元素的排序及有序链表的合并(选做) 链表的原地逆置(选做) 假定处理的线性表元素是int型的数据
时间: 2024-10-19 14:12:58 浏览: 26
在基于带头结点的链式存储结构中,我们可以创建一个单链表类来实现上述功能。下面是一个简单的Python示例:
```python
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 初始化为空链表
def initialize(self):
self.head = None
# 置空链表
def empty_list(self):
self.head = None
# 销毁链表
def destroy(self):
current = self.head
while current is not None:
next_node = current.next
del current
current = next_node
# 查找元素
def search(self, value):
current = self.head
found = False
while current and not found:
if current.value == value:
found = True
else:
current = current.next
return found
# 插入元素
def insert(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 删除元素
def delete(self, value):
if not self.head:
return
if self.head.value == value:
self.head = self.head.next
return
current = self.head
while current.next and current.next.value != value:
current = current.next
if current.next:
current.next = current.next.next
# 输出链表元素
def print_list(self):
elements = []
current = self.head
while current:
elements.append(current.value)
current = current.next
print(elements)
# 排序链表(这里假设是升序)
def sort_list(self):
if not self.head or not self.head.next:
return
current = self.head
while current.next:
smaller = current
larger = current.next
while larger and smaller.value > larger.value:
temp = smaller.value
smaller.value = larger.value
larger.value = temp
smaller = smaller.next
larger = larger.next
current = current.next
# 合并两个有序链表(选做)
def merge_sorted_lists(self, other_list):
if not self.head:
return other_list.head
elif not other_list.head:
return self.head
elif self.head.value < other_list.head.value:
self.head.next = self.merge_sorted_lists(other_list)
return self.head
else:
other_list.head.next = self.merge_sorted_lists(self)
return other_list.head
# 原地逆置链表(选做)
def reverse_list_in_place(self):
prev = None
current = self.head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.head = prev
# 使用示例
linked_list = LinkedList()
linked_list.insert(5) # 添加元素
linked_list.print_list() # 输出: [5]
linked_list.reverse_list_in_place() # 逆置链表
linked_list.print_list() # 输出: [5]
```
以上代码实现了一个基本的单向链表,包含了初始化、置空、销毁、查找、插入、删除、打印、排序、合并以及原地逆置的功能。对于排序部分,这里是冒泡排序的例子,实际项目中可能会选择更高效的算法如归并排序或快速排序。
阅读全文