#include <iostream> #include <cstdio> #include <cstdlib> #define MaxSize 50 using namespace std; typedef struct { char data[MaxSize]; int length; }SqList; void InitList(SqList * &L) { L=(SqList *)malloc(sizeof(SqList)); L->length=0; } void DestroyList (SqList * &L) { free(L); } bool ListEmpty(SqList * &L) { return (L->length==0); } int ListLength(SqList * &L) { return (L->length); } void DispList(SqList * &L) { int i; for(i=0;i<L->length;i++) { cout<<L->data[i]; } cout<<endl; } bool GetElem(SqList * &L,int i,char &e) { if((i<1)||(i>L->length)) return false; e=L->data[i-1]; cout<<e<<'\n'; return true; } int LocateElem(SqList * &L,char &e) { int i=0; while(i<L->length&&L->data[i]!=e) i++; if(i>L->length) return 0; else return i+1; } bool ListInsert(SqList * &L,int i,char &e) { int j; if(i<1||i>L->length+1) return false; i--; for(j=L->length;j>i;j--) L->data[j]=L->data[j-1]; L->data[i]=e; L->length++; return true; } void wc(SqList * &L,char a[]) { int j; for(j=0;a[j]!='\0';j++) { L->data[j]=a[j]; L->length++; } } bool ListDelete(SqList * &L,int i,char &e) { int j; if(i<1||i>L->length) return false; i--; e=L->data[i]; for(j=i;j<L->length-1;j++) L->data[j]=L->data[j+1]; L->length--; return true; } int main() { SqList *L; InitList(L); cout<<"初始化顺序表L"<<endl; char a[6]; cout<<"采用尾插法一次插入元素:"; gets(a); wc(L,a); cout<<"输出顺序表:"; DispList(L); cout<<"顺序表的长度为:"<<ListLength(L)<<'\n'; if(ListEmpty(L)==0) cout<<"顺序列表不为空!"<<'\n'; else cout<<"顺序列表为空!"<<'\n'; char e,ch,sh; int i,m,x; cout<<"查找第i个元素,请输入i:"; cin>>i; cout<<"输出顺序表的第"<<i<<"个元素= "; GetElem(L,3,e); cout<<"查找ch元素的位置,请输入ch:"; cin>>ch; cout<<"输出元素"<<ch<<"的位置:"<<LocateElem(L,ch)<<'\n'; cout<<"在第m个位置上插入元素sh,请输入m和sh: "; cin>>m>>sh; ListInsert(L,m,sh); cout<<"在顺序表第"<<m<<"个位置上插入元素"<<sh<<"后,输出顺序表:"; DispList(L); cout<<"删除顺序表第x个元素,请输入x:"; cin>>x; ListDelete(L,x,e);//还是同上 cout<<"删除顺序表第"<<x<<"个元素后,输出顺序表:"; DispList(L); DestroyList(L);//同上 cout<<"释放顺序表L!"; return 0; }