#include<iostream>
#include<malloc.h>
#include<stdlib.h>
using namespace std;
#define maxsize 100
typedef struct node
{
int data[maxsize];
int length;
}seqlist;
typedef seqlist *pseqlist;
pseqlist init_seqlist(void)
{
pseqlist seqlistpoint;
seqlistpoint=(pseqlist)malloc(sizeof(seqlist));
if(seqlistpoint)
seqlistpoint->length=0;
return(seqlistpoint);
}
void destroy_seqlist(pseqlist *seqlistpoint)
{
if(*seqlistpoint)
free(*seqlistpoint);
*seqlistpoint=NULL;
return;
}
int length_seqlist(pseqlist seqlistpoint)
{
if(seqlistpoint)
return(seqlistpoint->length);
return(-1);
}
int location_seqlist(pseqlist seqlistpoint,int x)
{
int i=0;
if(!seqlistpoint)
{
cout<<"表不存在"<<endl;
return(-1);
}
while(i<seqlistpoint->length&&seqlistpoint->data[i]!=x)
i++;
if(i>=seqlistpoint->length)
return 0;
else return(i+1);
}
int insert_seqlist(pseqlist seqlistpoint,int i,int x)
{
int j;
if(!seqlistpoint)
{
cout<<"表不存在"<<endl;
return(-2);
}
if(seqlistpoint->length>=maxsize)
{
cout<<"表溢出"<<endl;
return(-1);
}
if(i<1||i>seqlistpoint->length+1)
{
cout<<"插入位置不合法"<<endl;
return(0);
}
for(j=seqlistpoint->length-1;j>=i;j--)
seqlistpoint->data[j+1]=seqlistpoint->data[j];
seqlistpoint->data[i-1]=x;
seqlistpoint->length++;
return(-1);
}
void print_seqlist(pseqlist seqlistpoint)
{
for(int i=0;i<seqlistpoint->length;i++)
cout<<seqlistpoint->data[i]<<" ";
}
int delete_seqlist(pseqlist seqlistpoint,int i)
{
int j;
if(!seqlistpoint)
{
cout<<"表不存在"<<endl;
return(-1);
}
if(i<1||i>seqlistpoint->length)
{
cout<<"刪除位置不合法"<<endl;
return 0;
}
for(j=i;j<seqlistpoint->length;j++)
seqlistpoint->data[j-1]=seqlistpoint->data[j];
seqlistpoint->length--;
return (1);
}
void menu() { cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl; cout<<"輸出表長--------1/t/t"<<"輸出表--------2/t/t"<<"按值查找--------3/t/t"<<endl; cout<<"插入元素--------4/t/t"<<"刪除元素------5/t/t"<<"退出操作--------6/t/t"<<endl; cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl; cout<<endl; }
void main()
{
pseqlist seqlistpoint;
seqlistpoint=init_seqlist();
int x; cout<<"初始化成功/t";
cout<<"輸入數據"<<endl;
for(int i=1;i<6;i++)
{
cin>>x;
insert_seqlist(seqlistpoint,i,x);
}
menu();
while(1)
{
cin>>x;
switch(x)
{
case 1:
{
cout<<"表長爲"<<length_seqlist(seqlistpoint)<<endl<<endl;
menu();
} break;
case 2:
{
cout<<"輸出表"<<endl;
print_seqlist(seqlistpoint);
cout<<endl;
menu();
} break;
case 3:
{
int a;
cout<<"要想查找某一個元素的位置,請輸入他的值"<<endl;
cin>>a;
cout<<"查找位置爲"<<location_seqlist(seqlistpoint,a)<<endl;
cout<<endl;
menu();
} break;
case 4:
{
cout<<"要想在表中插入一個元素,請輸入它的位置和值"<<endl;
int m,n;
cin>>m>>n;
insert_seqlist(seqlistpoint,m,n);
cout<<"插入後輸出表"<<endl;
print_seqlist(seqlistpoint); cout<<endl;
menu();
} break;
case 5:
{
cout<<"要想在表中刪除一個元素,請輸入它的位置"<<endl;
int m;
cin>>m;
delete_seqlist(seqlistpoint,m);
cout<<"刪除後輸出表"<<endl;
print_seqlist(seqlistpoint); cout<<endl;
menu();
} break;
case 6:
{
destroy_seqlist(&seqlistpoint);
exit(1);
} break;
}
}
}