请编程实现一个对顺序表进行基本操作的系统,主要包括表的创建,输入,查询,取值,插入,删除和输出等操作
时间: 2024-05-21 09:10:48 浏览: 73
以下是Python语言的代码实现:
class SeqList:
def __init__(self, size):
self.maxsize = size # 顺序表的最大容量
self.num = 0 # 顺序表的元素个数
self.data = [None] * self.maxsize # 用列表存储顺序表的元素
def create(self):
print("请输入顺序表的元素,以空格分隔:")
elements = input().split()
for i in range(len(elements)):
self.data[i] = elements[i]
self.num += 1
def search(self, target):
for i in range(self.num):
if self.data[i] == target:
return i
return -1
def get(self, index):
if index < 0 or index >= self.num:
print("索引越界!")
return None
return self.data[index]
def insert(self, index, value):
if index < 0 or index > self.num:
print("索引越界!")
return
if self.num == self.maxsize:
print("顺序表已满,无法插入!")
return
for i in range(self.num, index, -1):
self.data[i] = self.data[i-1]
self.data[index] = value
self.num += 1
def delete(self, index):
if index < 0 or index >= self.num:
print("索引越界!")
return
for i in range(index, self.num-1):
self.data[i] = self.data[i+1]
self.data[self.num-1] = None
self.num -= 1
def output(self):
print("顺序表的元素为:", end="")
for i in range(self.num):
print(self.data[i], end=" ")
print()
# 测试代码
seqList = SeqList(10)
seqList.create()
seqList.output()
print("请输入要查询的元素:")
target = input()
index = seqList.search(target)
if index == -1:
print("未找到该元素!")
else:
print("该元素的下标为:", index)
print("请输入要取值的索引:")
index = int(input())
val = seqList.get(index)
if val is not None:
print("该索引对应的值为:", val)
print("请输入要插入的元素和插入位置,以空格分隔:")
value, index = input().split()
seqList.insert(int(index), value)
seqList.output()
print("请输入要删除的元素的索引:")
index = int(input())
seqList.delete(index)
seqList.output()
阅读全文