顺序表
#include<iostream>
#include<string.h>
using namespace std;
#define MAXSIZE 10000
typedef struct
{ char no[20];
char name[50];
float price;
}Book;
typedef struct
{ Book *elem;
int length;
}SqList;
int InitList(SqList &L)
{ L.elem=new Book[MAXSIZE];
if(!L.elem)exit(0);
L.length=0;
return 1;
}
int GetElem(SqList L,int i,Book &e)
{ if(i<1||i>L.length)
return 0;
e=L.elem[i-1];
return 1;
}
int LocateElem(SqList L,Book e)
{ int i;
for(i=0;i<L.length;i++)
if(strcmp(L.elem[i].no,e.no)==0)
return i+1;
return 0;
}
int ListInsert(SqList &L,int i,Book e)
{ int j;
if((i<1)||(i>L.length+1))
return 0;
if(L.length==MAXSIZE)
return 0;
for(j=L.length-1;j>=i-1;j--)
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
++L.length;
return 1;
}
int ListDelete(SqList &L,int i)
{ int j;
if((i<1)||(i>L.length))
return 0;
for(j=i;j<=L.length-1;j++)
L.elem[j-1]=L.elem[j];
--L.length;
return 1;
}
int main()
{ int i;
Book books[3]={{"no1","Chinese",10},{"no3","English",11},{"no5","Math",12}};
Book e;
SqList L;
InitList(L);
for(i=0;i<3;i++)
{ L.elem[i]=books[i];
L.length=3;
}
for(i=0;i<3;i++)
{ cout<<books[i].no<<" "<<books[i].name<<" "<<books[i].price<<endl;
}
GetElem(L,2,e);
cout<<e.no<<" "<<e.name<<" "<<e.price<<endl;
Book f={"no3","English",11};
cout<<LocateElem(L,f)<<endl;
Book insertBook={"no2","politics",11};
ListInsert(L,2,insertBook);
for(i=0;i<4;i++)
{ cout<<L.elem[i].no<<" "<<L.elem[i].name<<" "<<L.elem[i].price<<endl;
}
ListDelete(L,1);
for(i=0;i<3;i++)
{ cout<<L.elem[i].no<<" "<<L.elem[i].name<<" "<<L.elem[i].price<<endl;
}
}