#include<iostream>
using namespace std;
//任务描述:删除顺序表中大于x的元素。例如:线性表 L = (3,7,1,5,9,6,4) , x = 5执行算法后
//L 变为(3,1,5,4)
const int ListInitSize = 1;//线性表储存空间的初始分配量
const int ListInc = 1;//线性表储存空间的储存增量
struct SList //定义顺序表结构体
{
int * elem;
int length,listsize;
};
bool ListCreat(SList &L,int n,int a[])//创建顺序表,并向其中添加若干元素
{
L.elem = new int[n+ListInitSize];
if (L.elem == NULL)
return false; //若开辟内存失败,则返回false
L.length = n;
L.listsize = n+ListInitSize;
for (int i=0; i<n; i++)
L.elem[i] = a[i];
return true;
}
int read_list(int new_list[]) //从键盘中读取数据
{
cout <<"请输入顺序表中的元素,以回车分割,-1视为输入结束" << endl;
int i = -1;
while(1)
{
i++;
cin>>new_list[i];
if (new_list[i] == -1)
{
cout << "输入结束\n" << endl;
break;
}
}
return i;
}
void dele(SList &L,int x) //将顺序表中的元素比较并进行删除
{
int temp[L.length];
int j = 0;
int new_length = 0;
for ( ; j<L.length ; j++)
{
if (x>=L.elem[j])
{
temp[new_length] = L.elem[j];
new_length++;
}
}
L.elem = new int[new_length+ListInitSize];
for (int i = 0;i<new_length;i++)
L.elem[i] = temp[i];
L.listsize = new_length+ListInitSize;
L.length = new_length;
}
int main()
{
SList my_list;
// ListInit(my_list);
int new_list[20],number;
//要考虑输入元素个数大于20的情况,有待完善
number = read_list(new_list);
cout << "您输入了" << number << "个数字" << endl;
ListCreat(my_list,number,new_list) ? cout << "顺序表创建成功!" << endl : cout << "顺序表创建失败!" << endl;
cout << "请输入待比较的数字" << endl;
int compare_number;
cin >> compare_number;
dele(my_list,compare_number);
cout << "比较后元素的个数为:" << my_list.length << endl;
for (int i = 0;i<my_list.length;i++)
{
cout << "比较后第" << i+1 << "个元素为:" <<my_list.elem[i] << endl;
}
return 0;
}
顺序表(一)
最新推荐文章于 2022-03-09 08:30:00 发布