#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100 //初始数量为100
#define LISTINCREMENT 10
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
#define ERROR 0
#define OK 0
typedef int ElemType;
typedef struct{
ElemType *elem;
int length;
int listsize;
}Sqlist;
int main(){
Sqlist La;
int j=0,i;
ElemType elem,x;
Initlist_sq(La);
printf("please input the first elems of La:");
scanf("%d",&elem);
while(elem!=0){
Insert_sq(La,La.length+1,elem); //不太懂为什么是长度加1 ?
printf("please input the next elem of La:");
scanf("%d",&elem);
}
Tranver_sq(La);
return 0;
}
int Initlist_sq(Sqlist &L){
L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem) exit(OVERFLOW);
L.length =0; //不太懂为什么是初始长度为0?
L.listsize = LIST_INIT_SIZE;
return 0;
}
int Insert_sq(Sqlist &L,int i,ElemType e){ //不懂为什么是ElemType e 需要实例化吗?
ElemType *newbase,*q,*p;
if(i<1||i>L.length+1) return FALSE;//不懂为什么是length+1
if(L.length>L.listsize){ //不够需要加空间的
newbase = (ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newbase) exit(OVERFLOW);//what?
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
q = &(L.elem[i-1]);
for(p=&(L.elem[L.length-1]);p>=q;--p)*(p+1)=*p; //不懂啊
*q = e;
++L.length;
return OK;
}
int Tranver_sq(Sqlist &L){
int j;
if(L.length<1) return FALSE;
printf("线性表为:\n");
for(j=0;j<=L.length-1;j++){
printf("elem[%d]=%d\n",j,L.elem[j]);
}
return TRUE;
}