/**********************************************
顺序表的操作
BY YQG.06.3.6
***********************************************/
#include"stdio.h" #include"stdlib.h" #define LENG sizeof(struct List)/*注意这里不能为sizeof(sqlist*),其为指针类型。否则会弹框*/ #ifndef false #define false 0 #endif #ifndef true #define true 1 #endif typedef struct List { int elem[20]; int length; }sqlist; void InitList( sqlist **list); void DestroyList(sqlist**list); int ListEmpty(sqlist*list); int ListLength(sqlist*list); void DispList(sqlist*list); int GetElem(sqlist*list,int tem,int *item); int LocataElem(sqlist*list,int item); int ListInsert(sqlist **list,int tem,int item); int DeleteList(sqlist **list,int tem,int *item); void Input(sqlist **list); void main() { sqlist *itemlist; int item=0,data=0; InitList(&itemlist);/*注意这里叁数须为&itemlist, 即传入itemlist指针变量的地址, 否则InitList只针对局部的, 还有InitList声明为InitList(sqlist **list)*/ Input(&itemlist); DispList(itemlist); printf("/nInput the location:"); scanf("%d",&item); printf("/nInput the data:"); scanf("%d",&data); ListInsert(&itemlist,item,data); DispList(itemlist); getch(); } void Input(sqlist **list) { int item=0,i=0; //printf("/nInput the list number:"); //scanf("%d",&item); printf("/nInput the list(end with 0):"); (*list)->elem[i]=1; while((*list)->elem[i]!=0) scanf("%d",&((*list)->elem[i++])); (*list)->length=i; } void InitList(sqlist **list) { int i=0; (*list)=(sqlist*)malloc(LENG); (*list)->length=0; } void DestroyList(sqlist **list) { free(*list);/*注意这里释放的是LIST单元, 不是LIST单元的指针变量*/ } int ListEmpty(sqlist*list) { return(list->length==0); } int ListLength(sqlist*list) { return list->length; } void DispList(sqlist*list) { int i=0; for(;i length;i++) printf("%d ",list->elem[i]); } int GetElem(sqlist*list,int tem,int *item) { if(tem< 0 || tem>list->length) return false; (*item)=list->elem[tem-1]; return true; } int LocataElem(sqlist*list,int item) { int i=0; for(;i length;i++) if(list->elem[i]==item) break; if (i length) return i+1; /*找到返回*/ else return false; /*找不到返回*/ } int ListInsert(sqlist **list,int tem,int item) { int i=0; if(tem<0||tem > (*list)->length) return false; for(i=(*list)->length-1;i>=tem-1;i--) /*插入到ELEM{TEM-1]*/ { (*list)->elem[i+1]=(*list)->elem[i];/*注意“=”不能颠倒*/ } (*list)->elem[tem-1]=item; (*list)->length ++; return true; } /********************************************* //若这样 DeleteList(sqlist &list,int tem,int &item), //且这样DeleteList(&itemlist,2,item);调用 //程序没反映 ***********************************************/ int DeleteList(sqlist **list,int tem,int *item) { int i=0; if(tem<0||tem > (*list)->length) return false; (*item)=(*list)->elem[tem-1];/*return */ for(i=tem-1;i<(*list)->length;i++) { (*list)->elem[i] = (*list)->elem[i+1]; } (*list)->length--; return false; }