- #include<stdio.h>
- #include<stdlib.h>
- #define LIST_INIT_SIZE 100
- #define INCREMENT_SIZE 10
- typedef int DataType;
- typedef struct{
- DataType *elem;
- int length;
- int listsize;
- }sqlist,*plist;
- DataType initList(plist l)
- {
- l->elem = (DataType *)malloc(sizeof(DataType)*LIST_INIT_SIZE);
- if(!l->elem) return 0;
- l->length = 0;
- l->listsize = LIST_INIT_SIZE;
- return 1;
- }
- DataType insertList(plist l,int i, DataType e)
- {
- DataType *p;
- if(i < 1 || i > l->length+1) return 0;
- if(l->length >= l->listsize)
- {
- l->elem = (DataType *)realloc(l->elem,(LIST_INIT_SIZE+INCREMENT_SIZE)*sizeof(DataType));
- }
- for(p = l->elem + l->length-1; p >= l->elem + l->length-1; --p) *(p+1) = *p;
- *(l->elem+i-1) = e;
- l->length++;
- return 1;
- }
- DataType deleteList(plist l,int i, DataType *e)
- {
- DataType *p;
- if(i < 1 || i > l->length) return 0;
- *e = *(l->elem+i-1);
- for(p = l->elem+i-1;p <= l->elem+l->length; p++) *p = *(p-1);
- l->length--;
- }
- DataType locationList(plist l, DataType e)
- {
- DataType *p;
- int j = 0;
- for(p = l->elem;(p <= l->elem+l->length) ;p++)
- {
- ++j;
- if(*p == e)
- {
- return j;
- }
- }
- return j;
- }
- DataType mergeList(sqlist la,sqlist lb, plist lc)
- {
- DataType *pa,*pb,*pc;
- pa = la.elem;
- pb = lb.elem;
- lc->length = la.length + lb.length;
- pc = lc->elem = (DataType *) malloc(sizeof(DataType)*(lc->length));
- if(!lc->elem) return 0;
- while(pa <= la.elem + la.length-1 && pb <= lb.elem+lb.length-1)
- {
- if(*pa < *pb) *pc++ = *pa++;
- else *pc++ = *pb++;
- }
- while(pa <= la.elem+la.length-1) *pc++ = *pa++;
- while(pb <= la.elem+lb.length-1) *pc++ = *pb++;
- return 1;
- }
- void main()
- {
- sqlist l,la,lc;
- int i;
- initList(&l);
- insertList(&l,1,3);
- printf("the length is %d\\n",l.length);
- printf("\\n");
- printf("show list :\\n");
- for(i=0;i<l.length;i++)printf(" the %d number is %d\\n",i,l.elem[i]);
- initList(&la);
- insertList(&la,1,2);
- printf("\\n");
- printf("show list a:\\n");
- for(i=0;i<la.length;i++)printf(" the %d number is %d\\n",i,la.elem[i]);
- mergeList(l,la,&lc);
- printf("\\n");
- printf("show list c:\\n");
- for(i=0;i<lc.length;i++)printf(" the %d number is %d\\n",i,lc.elem[i]);
- printf("\\n");
- i = locationList(&l,3);
- printf("the location is: %d\\n",i);
- deleteList(&l,1,&i);
- printf("the delete number is %d\\n",i);
- printf("the length is %d\\n",l.length);
- }
- //该片段来自于http://www.codesnippet.cn/detail/1908201410238.html
来源: http://www.codesnippet.cn/detail/1908201410238.html