/*我们的计量方式,除下标从0开始外,其余都从1开始算,所以只有在涉及访问数组的时候,要注意是否要+1 或-1*/ #include <stdio.h> #define MAXSIZE 20 #define OK 1 #define ERROR 0 #define TRUE 1 #define FLASE 0 typedef struct { int No; int grade; } ElemType; typedef struct { ElemType data[MAXSIZE];//the max length of the list int length; }SqList; void InitList(SqList* L) { L->length = 0; } int GetElem(SqList* L,int i,ElemType* e) { if(L->length == 0 || i > L->length || i < 1) return ERROR; *e = L->data[i-1]; return OK; } int CreatList(SqList* L) { int i; printf("ready to create the list,please input the length\n"); scanf("%d",&L->length); if(L->length > MAXSIZE) fprintf(stderr,"out of memory!\n"); for(i = 0; i <= L->length - 1;i++) { printf("data %d= ",i+1); scanf("%d %d",&L->data[i].No,&L->data[i].grade); } } int InsertList(SqList*L,int i,ElemType* e) { int k; if(L->length == MAXSIZE) return ERROR; if(i < 1 || i > L->length + 1) return ERROR; if(i <= L->length) { for(k = L->length; k >= i; k--) { L->data[k] = L->data[k - 1]; } } L->data[i - 1] = *e; L->length++; return OK; } int DeleteList(SqList* L,int i) { int k; if(L == NULL || i > L->length) return ERROR; for(k = i; k <= L->length;k++ ) { L->data[k - 1] = L->data[k]; } L->length --; return OK; } void ShowList(SqList* L) { int i; for(i = 0; i <= L->length - 1;i++) { printf("%d %d \n",L->data[i].No,L->data[i].grade); } } int ListLength(SqList* L) { return L->length; } /*return the location(num) of the element*/ int LocateElem(SqList* L,ElemType* e) { int i,res; for(i = 0; i < L->length; i++) { if(L->data[i].No == e->No && L->data[i].grade == e->grade) res = i+1; else res = -1; } return res; } /*combine two lists,if the element in l2 is not existent in l1,insert the element into l1*/ void CombineList(SqList* L1,SqList* L2) { int L1_len,L2_len,i; ElemType e; L1_len = ListLength(L1); L2_len = ListLength(L2); for(i = 1; i <= L2_len;i++) { GetElem(L2,i,&e); if(LocateElem(L1,&e) == -1) { InsertList(L1,i,&e); } } } int main() { SqList L1; SqList L2; InitList(&L1); InitList(&L2); printf("SqList L1:\n"); CreatList(&L1); printf("SqList L2:\n"); CreatList(&L2); CombineList(&L1,&L2); ShowList(&L1); return 0; }结果示意:
原文地址:http://blog.csdn.net/xingzhibo/article/details/42709433