《數據結構》線性表僞碼變代碼

《數據結構》線性表僞碼變代碼
前幾天讀ruby049中,array.c時,發現和數據結構課本上的實現很像。於是今天就把嚴教授課本上的僞碼輸入到計算機中,進行了調試。
代碼如下:
#define LIST_INIT_SIZE 100
#define LISTINCE 10
#include<stdio.h>
#include<stdlib.h>

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

int InitList_Sq(SqList *L)
{
    L->elem=(ElemType *)malloc(LIST_INIT_SIZE *sizeof(ElemType));
    if (!L->elem) exit(-1);
    L->length=0;
    L->listsize=LIST_INIT_SIZE;
    return 0;
}
void Print_Sq(SqList *L)
{
    int i;
    for(i=0;i<L->length;i++){
        printf("%d,",L->elem[i]);
    }
    printf("\n");
}
int ListInsert_Sq(SqList *L,int i,ElemType e)
{
    if (i<1 || i>L->length+1) return -1;
    if (L->length >= L->listsize){
        ElemType *newbase;
        newbase=(ElemType *)(realloc(L->elem,(L->listsize+LISTINCE)*sizeof(ElemType)));
        if (!newbase) exit(-1);
        L->elem=newbase;
        L->listsize +=LISTINCE;
    }
    ElemType *q=&(L->elem[i-1]);
    ElemType *p;
    for(p=&(L->elem[L->length-1]);p>=q;--p)
        *(p+1)=*p;
    *q=e;
    L->length++;
    return 0;
}
int ListDelete_Sq(SqList *L,int i,ElemType *e)
{
    if (i<1 || i>L->length) return -1;
    ElemType *p=&(L->elem[i-1]);
    *e=*p;
    ElemType *q=&(L->elem[L->length-1]);
    for(++p;p<=q;++p)
        *(p-1)=*p;
    L->length--;
    return 0;
}
int main()
{
    SqList a;
    int status=InitList_Sq(&a);
    if (status==0) printf("ok\n");
    Print_Sq(&a);
    ListInsert_Sq(&a,1,8);
    ListInsert_Sq(&a,2,18);
    ListInsert_Sq(&a,3,28);
    Print_Sq(&a);
    ElemType e;
    ListDelete_Sq(&a,2,&e);
    Print_Sq(&a);
    printf("hello\n");
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章