#include<iostream>
#include<stdio.h>
#define MAXSIZE 100
using namespace std;
typedef struct
{
int *data;
int length;
} Sqlist;
void Init(Sqlist &L)
{
L.data=new int[MAXSIZE];
if(!L.data)
cout<<"空间分配失败!\n";
else
{
cout<<"空间分配成功!\n";
L.length=0;
}
}
void Creat(Sqlist &L)
{
cout<<"顺序表建立成功\n\n请输入表长:";
cin>>L.length;
cout<<"表中元素为:";
for(int i=0; i<L.length; i++)
cin>>L.data[i];
}
void Print(Sqlist &L)
{
for(int i=0; i<L.length; i++)
cout<<L.data[i]<<" ";
cout<<endl<<endl;
}
void Insert(Sqlist &L,int index,int x)
{
if(index<1||index>L.length+1)
cout<<"位置不合理"<<endl;
else if(L.length==MAXSIZE)
cout<<"表满"<<endl;
else
{
for(int j=L.length-1; j>=index-1; j--)
L.data[j+1]=L.data[j];
L.data[index-1]=x;
L.length++;
}
Print(L);
}
void Delete(Sqlist &L,int index)
{
if(index<1||index>L.length)
cout<<"位置不合理"<<endl;
else if(L.length==0)
cout<<"空表"<<endl;
else
{
for(int j=index; j<=L.length-1; j++)
L.data[j-1]=L.data[j];
L.length--;
}
Print(L);
}
void IdSearch(Sqlist &L,int index)
{
if(index<1||index>L.length)
cout<<"查找的位置不存在"<<endl<<endl;
else
cout<<L.data[index-1]<<endl<<endl;
}
int ValueSearch(Sqlist &L,int e)
{
for(int i=0; i<L.length; i++)
if(L.data[i]==e)
return i+1;
return 0;
}
int main()
{
int Insert_Number,Insert_Location,Delete_Location,Seach_Id,Seach_Value;
Sqlist L;
Init(L);
Creat(L);
Print(L);
cout<<"请输入要插入的结点值及其位置:";
cin>>Insert_Number>>Insert_Location;
Insert(L,Insert_Location,Insert_Number);
cout<<"请输入要删除的结点的位置:";
cin>>Delete_Location;
Delete(L,Delete_Location);
cout<<"请输入要查找的结点的序号:";
cin>>Seach_Id;
IdSearch(L,Seach_Id);
cout<<"请输入要查找的结点的值:";
cin>>Seach_Value;
if(!ValueSearch(L,Seach_Value))
cout<<"输入的元素"<<Seach_Value<<"不在顺序表中"<<endl<<endl;
else
cout<<"输入的元素"<<Seach_Value<<"在顺序表的第"<<ValueSearch(L,Seach_Value)<<"位"<<endl<<endl;
}