《数据结构》线性表伪码变代码

《数据结构》线性表伪码变代码
前几天读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;
}

 

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