线性表中的顺序表的9种基本运算的算法的python程序实现
时间: 2024-09-18 16:14:37 浏览: 44
线性表的顺序表是一种简单的数据结构,其元素按特定顺序存储在连续的内存空间中。以下是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)
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = Node(data)
# 删除指定位置的节点
def delete_at_pos(self, pos):
if pos < 0 or pos >= self.length():
return
if pos == 0:
self.head = self.head.next
else:
current = self.head
for _ in range(pos - 1):
current = current.next
current.next = current.next.next
# 查找并返回某个元素
def find(self, target):
current = self.head
while current:
if current.data == target:
return current
current = current.next
return None
# 获取指定位置的元素
def get(self, pos):
if pos < 0 or pos >= self.length():
raise IndexError("Index out of bounds")
current = self.head
for _ in range(pos):
current = current.next
return current.data
# 设置指定位置的元素
def set(self, pos, value):
if pos < 0 or pos >= self.length():
raise IndexError("Index out of bounds")
current = self.head
for _ in range(pos):
current = current.next
current.data = value
# 获取链表长度
def length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
# 判断链表是否为空
def is_empty(self):
return self.head is None
# 对链表进行升序排序
def sort(self):
if not self.is_empty():
self.head = self.merge_sort(self.head)
# 归并排序
def merge_sort(self, node):
if node and node.next:
mid = self.get_mid(node)
second_half = self.get_mid(mid.next)
mid.next = None
return self.merge(self.merge_sort(node), self.merge_sort(second_half))
return node
# 获取中间节点
def get_mid(self, node):
slow = fast = node
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
# 合并两个已排序链表
def merge(self, first, second):
result = None
if not first:
return second
elif not second:
return first
if first.data <= second.data:
result = first
result.next = self.merge(first.next, second)
else:
result = second
result.next = self.merge(first, second.next)
return result
# 示例
linked_list = LinkedList()
# 添加操作...
```
阅读全文