您好,欢迎访问三七文档
当前位置:首页 > 金融/证券 > 金融资料 > c语言顺序表实现完整版
#includestdio.h#includestdlib.h#includemalloc.h#defineLIST_INIT_SIZE100#defineLISTINCREMENT10typedefintElemtype;typedefintStatus;typedefstruct{Elemtype*elem;intlength;intlistsize;}SqList;//定义顺序表类型StatusInitList_Sq(SqList&L)//初始化顺序表{L.elem=(Elemtype*)malloc(LIST_INIT_SIZE*sizeof(Elemtype));L.length=0;L.listsize=LIST_INIT_SIZE;return1;}voidCreateList(SqList&L)//创建顺序表{inti;printf(请输入你要创建的顺序表元素个数);scanf(%d,&L.length);printf(请输入你要创建的顺序表:\n);for(i=0;iL.length;i++)scanf(%d,&L.elem[i]);}voidprint(SqList&L)//输出顺序表{inti;for(i=0;iL.length;i++)printf(%3d,L.elem[i]);}Statuslocation(SqListL,Elemtypee)//查找元素的位置{inti=0;while(L.elem[i]!=e&&iL.length)i++;if(iL.length)return-1;elsereturni+1;//因为c语言是从下标0开始的当i=0时实际上是顺序表的第i+1个元素}StatusListInsert_Sq(SqList&L,inti,Elemtypee)//在顺序表的第i个位置插入值为e的元素{Elemtype*newbase,*q,*p;if(i1||iL.length+1)return0;if(L.length=L.listsize){newbase=(Elemtype*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(Elemtype));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;return1;}StatusListDelect_Sq(SqList&L,inti,Elemtypee)//在顺序表的第i个位置删除值为e的元素并返回e的值{Elemtype*q,*p;if(i1||(iL.length))return0;p=&(L.elem[i-1]);e=*p;q=L.elem+L.length-1;for(++p;p=q;++p)*(p-1)=*p;--L.length;return1;}voidCombine(SqListLa,SqListLb,SqList&Lc)//将两个非递减的顺序表合并成一个顺序表,合并后元素也按值非递减排列{Elemtype*pa_last,*pb_last,*pa,*pb,*pc;pa=La.elem;pb=Lb.elem;Lc.listsize=Lc.length=La.length+Lb.length;pc=Lc.elem=(Elemtype*)malloc(Lc.listsize*sizeof(Elemtype));pa_last=La.elem+La.length-1;pb_last=Lb.elem+Lb.length-1;while(pa=pa_last&&pb=pb_last){if(*pa=*pb)*pc++=*pa++;else*pc++=*pb++;}while(pa=pa_last)*pc++=*pa++;while(pb=pb_last)*pc++=*pb++;}voidmain(){SqListla,lb,lc,ld;inti,j;Elemtypee;InitList_Sq(la);CreateList(la);print(la);printf(请输入要查找的元素:\n);scanf(%d,&e);j=location(la,e);printf(该元素的位置为%d\n,j);printf(请输入要插入的位置和元素:\n);scanf(%d%d,&i,&e);ListInsert_Sq(la,i,e);printf(输出插入后的顺序表:\n);print(la);printf(请输入要删除的位置:\n);scanf(%d,&i);ListDelect_Sq(la,i,e);printf(删除的那个元素是:%d\n,e);printf(输出删除后的顺序表:\n);print(la);InitList_Sq(lb);CreateList(lb);print(lb);InitList_Sq(lc);CreateList(lc);print(lc);InitList_Sq(ld);Combine(lb,lc,ld);printf(合并后的顺序表为:\n);print(ld);}
本文标题:c语言顺序表实现完整版
链接地址:https://www.777doc.com/doc-3818369 .html