순차 선형 표 (C 언어 구현)

10520 단어 데이터 구조
#include 
#include 
#include 

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define LIST_INIT_SIZE 100
#define LIST_INCREMENT 10

typedef int Status;
typedef int ElemType;

typedef struct{
    ElemType *elem;
    int length;
    int listsize;
}SqList;

Status InitList_Sq(SqList *L);
Status InsertList_Sq(SqList *L, int i, ElemType e);
Status DeleteList_Sq(SqList *L, int i, ElemType *e);
int LocateElem_Sq(SqList *L, ElemType e);
void MergeList_Sq(SqList La, SqList Lb, SqList *Lc);
void printList_Sq(SqList *L);

int main(){
    SqList L1,L2,L3;
    SqList *La,*Lb,*Lc;
    ElemType a;
    ElemType *e;
    int index = -1;
    e = &a;
    La = &L1;
    Lb = &L2;
    Lc = &L3;
    InitList_Sq(La);
    InitList_Sq(Lb);
    InitList_Sq(Lc);
    printf("              :
"
); InsertList_Sq(La, 1, 5); InsertList_Sq(La, 2, 8); InsertList_Sq(La, 3, 2); printList_Sq(La); printf("
"
); DeleteList_Sq(La, 2, e); printf(" :%d
:
"
,*e); printList_Sq(La); printf(" 2
"
); index = LocateElem_Sq(La, 2); printf(" 2 :
%d"
, index); printf(" Lb :
"
); InsertList_Sq(Lb, 1, 7); InsertList_Sq(Lb, 2, 8); InsertList_Sq(Lb, 3, 3); printList_Sq(Lb); printf("
"
); MergeList_Sq(*La, *Lb, Lc); printList_Sq(Lc); printf("
"
); system("PAUSE"); return 0; } Status InitList_Sq(SqList *L){ L->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); if(!L->elem) exit(OVERFLOW); L->length = 0; L->listsize = LIST_INIT_SIZE; return OK; } Status InsertList_Sq(SqList *L, int i, ElemType e){ ElemType *p, *q, *base; if(i<1 || i>L->length+1) return ERROR; if(L->length >= L->listsize){ base = (ElemType *)realloc(L->elem, (L->length + LIST_INCREMENT) * sizeof(ElemType)); if(!base) exit(OVERFLOW); L->listsize += LIST_INCREMENT; } q = &(L->elem[i-1]); for(p=&(L->elem[L->length-1]); p>=q; --p) *(p+1) = *p; *q = e; ++L->length; return OK; } Status DeleteList_Sq(SqList *L, int i, ElemType *e){ ElemType *p,*q; if(i<1 || i>L->length) return ERROR; p = &(L->elem[i-1]); *e = *p; q = &(L->elem[L->length-1]); for(++p; p<=q;++p) *(p-1) = *p; --L->length; return OK; } int LocateElem_Sq(SqList *L, ElemType e){ ElemType *p; int i; i = 1; p = L->elem; while(i <= L->length && e!= *p++) ++i; if(i <= L->length) return i; else return 0; } void MergeList_Sq(SqList La, SqList Lb, SqList *Lc){ ElemType *pa, *pb, *pc, *pa_last, *pb_last; pa = La.elem; pb = Lb.elem; Lc->listsize = Lc->length = La.length + Lb.length; pc = Lc->elem = (ElemType *)malloc(Lc->length * sizeof(ElemType)); if(!pc) exit(OVERFLOW); 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++; } void printList_Sq(SqList *L){ int i; for(i=0; ilength; ++i) printf("%d ", L->elem[i]); printf("
"
); }

좋은 웹페이지 즐겨찾기