题目描述
实现顺序表的用C++语言和类实现顺序表
属性包括:数组、实际长度、最大长度(设定为1000)
操作包括:创建、插入、删除、查找
类定义参考
输入
第1行先输入n表示有n个数据,即n是实际长度;接着输入n个数据
第2行输入要插入的位置和新数据
第3行输入要插入的位置和新数据
第4行输入要删除的位置
第5行输入要删除的位置
第6行输入要查找的位置
第7行输入要查找的位置
输出
数据之间用空格隔开
第1行输出创建后的顺序表内容,包括顺序表实际长度和数据
每成功执行一次操作(插入或删除),输出执行后的顺序表内容
每成功执行一次查找,输出查找到的数据
如果执行操作失败(包括插入、删除、查找等失败),输出字符串error,不必输出顺序表内容
样例输入
6 11 22 33 44 55 66
3 777
1 888
1
9
0
5
样例输出
6 11 22 33 44 55 66
7 11 22 777 33 44 55 66
8 888 11 22 777 33 44 55 66
7 11 22 777 33 44 55 66
error
error
44
提示
第i个位置是逻辑意义的位置,从1开始,在实际编程用数组,从0开始,对应数组i-1位置
直接看代码
#include<iostream>
#include<cstdlib>
using namespace std;
#define INCREAMENT_SIZE 10
#define ok 1
#define error 0
class SeqList {
private:
int* list;
int maxsize;//最大长度
int size;//实际长度
public:
SeqList();
~SeqList();
int getSize();
int list_insert(int i, int item);//让item成为第i个元素
int list_del(int i);//删除第i个元素
int getElement(int i);//得到第i个元素
void list_display();//打印list
};
void SeqList::list_display() {
cout << size << ' ';
for (int i = 0; i < size; i++) {
cout << list[i] << ' ';
}
cout << endl;
}
int SeqList::getElement(int i) {
//判断i的可行性
if (i<1 || i>size) {
return 0;
}
return list[i - 1];
}
int SeqList::list_del(int i) {
//判断i的可行性
if (i<1 || i>size) {
return 0;
}
for (int j = i-1; j < size-1; j++) {
list[j] = list[j + 1];//从前往后遍历赋值
}
size--;//删除成功
return 1;
}
int SeqList::list_insert(int i, int item) {
//判断i的可行性
if (i<1 || i>size+1) {
return 0;
}
//先判断表还能不能插入元素
if (size == maxsize) {//已经达到最大元素个数了
//重新分配空间
list = (int*)realloc(list, (maxsize + INCREAMENT_SIZE) * sizeof(int));
if (list == nullptr) {
exit(1);//分配失败
}
maxsize += INCREAMENT_SIZE;//空间多了
}
for (int j = size; j >= i; j--) {
list[j] = list[j - 1];//从后往前遍历赋值空出位置插入
}
list[i - 1] = item;
size++;//插入成功
return 1;
}
int SeqList::getSize() {
return size;
}
SeqList::SeqList() {//初始化
maxsize = 1000;
size = 0;
list = (int*)malloc(maxsize * sizeof(int));
if (list == nullptr) {//分配失败
exit(1);
}
}
SeqList::~SeqList() {
free(list);//释放空间
}
int main()
{
SeqList List;
int n, ele, where;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> ele;
List.list_insert(i, ele);
}
List.list_display();
for (int i = 0; i < 2; i++) {//插入
cin >> where >> ele;
int check = List.list_insert(where, ele);
if (check==0) {
cout << "error" << endl;
}
else {
List.list_display();
}
}
for (int i = 0; i < 2; i++) {//删除
cin >> where;
int check = List.list_del(where);
if (check == 0) {
cout << "error" << endl;
}
else {
List.list_display();
}
}
for (int i = 0; i < 2; i++) {//查找
cin >> where;
int check = List.getElement(where);
if (check == 0) {
cout << "error" << endl;
}
else {
cout << check << endl;
}
}
return 0;
}