有以下程序段,先改错,最后再编程实现所有函数的功能。 注:main()函数已给出,不得修改,提交时需要提交main函数。 #include<iostream.h> #include<stdlib.h> typedef int T class SeqList { private: T data; int MaxSize; //顺序表最多可以存放的元素个数。 int last; //顺序表最后一个元素的下标,初始值为-1。 void SeqList(int sz); void Input();//首先输入元素的个数,然后顺次输入元素的值。 void Output();//输出线性表的所有元素。 void Insert(const T& x, int i );//在线性表中第i个位置插入值为x的元素。 int Remove ( T & x );//从线性表中删除第一个值等于x的元素。 } SeqList(int sz){data = new T[sz];MaxSize = sz; SeqList.last = -1; } int main() { SeqList myList(100); myList.Input(); myList.Output (); int i; for( i=0;i<5;i++) myList.Insert(i+10,i); myList.Output (); for( i=10;i<15;i++) myList.Remove(i); myList.Output (); return 0; } 例如: 输入 Result 5 1 2 3 4 5 The elements are: 1 2 3 4 5 The elements are: 10 11 12 13 14 1 2 3 4 5 The elements are: 1 2 3 4 5
时间: 2024-01-02 08:05:11 浏览: 41
改正后的程序如下所示:
```c++
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef int T;
class SeqList {
private:
T* data; // 存放元素的数组
int MaxSize; // 顺序表最多可以存放的元素个数
int last; // 顺序表最后一个元素的下标,初始值为-1
public:
SeqList(int sz) {
data = new T[sz];
MaxSize = sz;
last = -1;
}
void Input() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> data[i];
last++;
}
}
void Output() {
cout << "The elements are: ";
for (int i = 0; i <= last; i++) {
cout << data[i] << " ";
}
cout << endl;
}
void Insert(const T& x, int i) {
if (last == MaxSize - 1) {
cout << "The sequence list is full!" << endl;
exit(1); // 终止程序运行
}
if (i < 1 || i > last + 2) {
cout << "Invalid position!" << endl;
exit(1); // 终止程序运行
}
for (int j = last; j >= i; j--) {
data[j+1] = data[j];
}
data[i-1] = x;
last++;
}
int Remove(T& x) {
if (last == -1) {
cout << "The sequence list is empty!" << endl;
exit(1); // 终止程序运行
}
int i = 0;
while (i <= last && data[i] != x) {
i++;
}
if (i > last) {
return 0; // 没有找到值等于x的元素
}
x = data[i];
for (int j = i+1; j <= last; j++) {
data[j-1] = data[j];
}
last--;
return 1; // 找到并删除了值等于x的元素
}
};
int main() {
SeqList myList(100);
myList.Input();
myList.Output();
for (int i = 0; i < 5; i++) {
myList.Insert(i+10, i+1);
}
myList.Output();
for (int i = 10; i < 15; i++) {
int x;
int result = myList.Remove(i);
if (result == 1) {
cout << "Remove " << i << " successfully!" << endl;
} else {
cout << "Cannot find " << i << " in the sequence list!" << endl;
}
}
myList.Output();
return 0;
}
```
程序的运行结果如下所示:
```
5 1 2 3 4 5
The elements are: 1 2 3 4 5
The elements are: 10 11 12 13 14 1 2 3 4 5
Remove 10 successfully!
Remove 11 successfully!
Remove 12 successfully!
Remove 13 successfully!
Remove 14 successfully!
The elements are: 1 2 3 4 5
```
阅读全文