线性表之有序表
所谓有序表,是指这样的线性表,其中所有的元素以递增或递减的方式排列,并且规定有序表中不存在元素值相同的元素!
#include<iostream> using namespace std; int ListInsert(SqList *&L,ElemType e) //用顺序表存储有序表,只有ListInsert()有所差异,其余相同 { int i=0,j; while(i<L->length&&L->data[i]<e) i++; if(L->data[i]==e) return 0; for(j=ListLength(L);j>i;j--) L->data[j]=L->data[j-1]; L->data[i]=e; L->length++; return 1; } //将有序表LA和LB合并成一个有序表LC,要求不破坏原有表的LA和LB p54例题2.11 void UnionList(SqList *LA,SqList *LB,SqList *&LC) //采用顺序表存储有序表 { int i=0,j=0,k=0; LC=(SqList *)malloc (sizeof(SqList)); LC->length=0; while(i<LA->length&&j<LB->length) { if(LA->data[i]<LB->data[j]) { LC->data[k]=LA->data[i]; i++; k++; } else { LC->data[k]=LB->data[j]; j++; k++; } } while(i<LA->length) { LC->data[k]=LA->data[i]; i++; k++; } while(j<LB->length) { LC->data[k]=LB->data[j]; i++; j++; } LC->length=k; } void UnionList(LinkList *LA,LinkList *LB,LinkList *&LC) { LinkList *pa=LA->next; LinkList *pb=LB->next; LinkList *pc,*s; LC=(LinkList *)malloc (sizeof(LinkList)); pc=LC; while(pa!=NULL&&pb!=NULL) { if(pa->data<pb->data) { s=(LinkList *)malloc(sizeof(LinkList)); s->data=pa->data; pc->next=s; pc=s; pa=pa->next; } else { s=(LinkList *)malloc(sizeof(LinkList)); s->data=pb->data; pc->next=s; pc=s; pb=pb->next; } } while(pa!=NULL) { s=(LinkList *)malloc(sizeof(LinkList)); s->data=pa->data; pc->next=s; pc=s; pa=pa->next; } while(pb!=NULL) { s=(LinkList *)malloc(sizeof(LinkList)); s->data=pb->data; pc->next=s; pc=s; pb=pb->next; } pc->next=NULL; } void Commnode(LinkList *&LA,LinkList *LB,LinkList *LC)//P55 例题2.12 { LinkList *pa=LA->next,*pb=LB->next,*pc=LC->next,*q,*r; LA->next=NULL; r=LA; while(pa!=NULL) { while(pb!=NULL&&pa->data>pb->data) { pb=pb->next; } while(pc!=NULL&&pa->datapa->data>pc->data) { pc=pc->next; } if(pb!=NULL&&pc!=NULL&&pa->data==pb->data&&pa->data==pc->data) { r->next=pa; r=pa; pa=pa->next; } else { q=pa; pa=pa->next; free(q); } } r->next=NULL; }