1. 线性表(用可动态分配的一维数组实现)

来源:互联网 发布:高尔夫球运动分析软件 编辑:程序博客网 时间:2024/06/11 16:54
#include<stdio.h>#include<stdlib.h>//2.2线性表的顺序表示和实现//用  可动态分配的一维数组//线性表的动态分配顺序存储结构#define LIST_INIT_SIZE  100#define LISTINCREMENT  10#define OK 0#define NO 1#define ERROR 2typedef int ElemType ;typedef bool Status;// elem---element 元素 typedef struct{ElemType *elem;int lengh;int listsize;}SqList;//sf 2.3//构造一个空的线性表Status InitList(SqList &L){L.listsize=LIST_INIT_SIZE;L.lengh=0;L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));if(!L.elem) {printf("内存非配失败");exit(NO);}return  OK;}//////sf2.4//在顺序表中的第i个位置插入一个新元素eStatus ListInsert_Sq(SqList &L,int i,ElemType e){//默认第一个位置 对应线性表的 第0个元素if(i<1 || i>L.lengh+1) { printf("i值不合法");  return ERROR; }if(L.lengh>=L.listsize) {ElemType *newbase= (ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));if(!newbase) {  exit(NO);}L.elem=newbase;L.listsize+=LISTINCREMENT;}if(i>1){ElemType *q=& (L.elem[i-1]);for(ElemType *p=&(  L.elem[L.lengh-1]  );p>=q;p--  )*(p+1)=*p;*q=e;}else L.elem[0]=e;++L.lengh;return OK;}//sf 2.5//在顺序线性表L中删除第i个元素Status ListDelete_Sq(SqList &L,int i){if(i<1 || i>L.lengh)  return ERROR;for(ElemType *p=&L.elem[i];p<=&L.elem[L.lengh-1];p++)*(p-1)=*p;L.lengh--;return OK;}//sf2.6//在线性表中 寻找 符合 compare() 的元素e的对应位序Status LocateElem_Sq(SqList &L,ElemType e,Status *compare(ElemType,ElemType)){int i=0;ElemType *p=L.elem;while(i<=L.lengh && !(*compare)(*p,e))  {p++;i++;}if(i<=L.lengh )  return i;return 0;}//sf 2.7//顺序表的合并//归并La Lb 得到新的顺序线性表Lc,Lc的值也按值非递减的顺序排列//值非递减 : 递增+包含相等元素void MergeList_Sq(SqList La,SqList Lb,SqList &Lc){//默认 Lc是已经存在的空表ElemType *pa,*pb,*pc,*a_last,*b_last;pa=La.elem;   pb=Lb.elem;Lc.listsize=Lc.lengh=La.lengh+Lb.lengh;//malloc for cpc=Lc.elem=(ElemType *)malloc(Lc.listsize*sizeof(ElemType));if(!pc) { exit(NO);}//接下来就是归并了,很经典的归并思路a_last=pa+La.lengh-1;b_last=pb+Lb.lengh-1;while(pa<=a_last && pb<=b_last){if(*pa<*pb)  *pc++=*pa++;else *pc++=*pb++;}while(pa<=a_last) *pc++=*pa++;while(pb<=b_last) *pc++=*pb++;}////void Output_Sq(SqList &L){//   假设元素类型为intfor(int i=0;i<L.lengh;i++)printf("%d   ",L.elem[i]);putchar(10);}//by zhaoyang 2014.4.14int main(){SqList A,B,C;InitList(A);InitList(B);InitList(C);for(int i=1;i<=10;i++){ListInsert_Sq(A,i,i);ListInsert_Sq(B,i,i);}Output_Sq(A);Output_Sq(B);MergeList_Sq(A,B,C);Output_Sq(C);}


0 0
原创粉丝点击