顺序表的实现和测试
要求
编写建表、插入元素、删除元素、合并有序表、表元素输出等功能并进行功能测试。
代码如下
#include <stdio.h>
#include<stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
int max,min,n,i,k,num;
int array[100];
void buildlist(int *array,int n)
{
cout <<"输入数组元素:"<<endl;
for(int i=0;i<n;i++)
cin>>array[i];
}
void showdlist(int *array,int n)
{
if(n<=0)
{
cout <<"数组为空数组"<<endl;
}
else
{
cout <<"数组元素:"<<endl;
for(int i=0;i<n;i++)
cout<<array[i]<<" ";
cout<<endl;
}
}
int main (){
while (1){
cout <<"【输入1建表,输入2插入元素,输入3删除元素,输入4合并表,输入5输出表,输入0退出】"<<endl;
cin>>num;
if(num==1)
{
cout <<"输入数组大小:"<<endl;
cin>>n;
buildlist(array,n);
cout <<"建表完成"<<endl;
}
else if(num==5)
showdlist(array,n);
else if (num==2)
{
cout <<"输入要插入的元素"<<endl;
cin>>k;
array[n]=k;
n=n+1;
cout <<"插入完成"<<endl;
}else if(num==3)
{
cout <<"输入要删除的元素"<<endl;
cin>>k;
int t=0;
for(int i=0;i<n;i++)
{
if(array[i]==k&&i!=n-1)
{
for(int j=i;j<n;j++)
{
array[j]=array[j+1];
}
t++;
i--;
} else if(array[i]==k&&i==n-1){
n=n-1;
}
}
n=n-t;
} else if(num==4)
{
int a[100];
cout <<"输入要合并的数组的大小:"<<endl;
int othern;
cin>>othern;
cout <<"输入要合并的数组的元素:"<<endl;
for(int i=0;i<othern;i++)
{
cin>>a[i];
}
for(int i=n;i<n+othern;i++)
{
array[i]=a[i-n];
}
n=n+othern;
cout <<"合并完成"<<endl;
}
else if (num==0)
{
break;}
else{
cout<<"输入违法,重新输入"<<endl;
}
}
system("pause");
return 0;
}
运行图如下