数据结构线性表的链式存储(纯代码)

数据结构线性表的链式存储(纯代码)

#include
#include
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0

typedef int datatype;//数据类型
typedef int status;//状态码
typedef struct Node{
     
    datatype data;
    struct Node *next;
}Node;
typedef struct Node *LinkList;//定义linklist
//初始化
status initlist(LinkList *L){
     
    *L = (LinkList)malloc(sizeof(Node));
    if(!(*L)){
     
        return ERROR;
    }
    (*L)->next = NULL;
    return OK;
}
//置空
status ClearList(LinkList *L){
     
    LinkList p,q;
    p = (*L)->next;
    while(p){
     
        q = p->next;
        free(p);
        p = q;
    }
    (*L)->next = NULL;
    return OK;
}
//返回元素个数
int ListLength(LinkList L){
     
    int i=0;
    LinkList p = L->next;
    while(p){
     
        i++;
        p = p->next;
    }
    return i;
}
//头插法
void CreateListHeader(LinkList *L,int n){
     
    LinkList p;
    int i;
    (*L)->next = NULL;
    for(i=0;i<n;i++){
     
        p = (LinkList)malloc(sizeof(Node));
        p->data = i;
        p->next = (*L)->next;
        (*L)->next = p;
    }
}
//尾插法
void CreateListTail(LinkList *L,int n){
     
    LinkList p,r;
    int i;
    *L = (LinkList)malloc(sizeof(Node));
    r = *L;
    for(i=0;i<n;i++){
     
        p = (LinkList)malloc(sizeof(Node));
        p->data = i;
        r->next = p;
        r = p;
    }
    r->next = NULL;
}
//返回第几个数值
status GetElem(LinkList L,int i,datatype *e){
     
    LinkList p;
    int j = 1;
    p  = L->next;
    while(p&&j<i){
     
        p = p->next;
        ++j;
    }
    if(!p||j>i){
     
        return ERROR;
    }
    *e = p->data;
    return OK;
}
//删除某个数据
status DelElem(LinkList *L,int n){
     
    LinkList p,q;
    p = *L;
    int j = 1;
    while(p->next&&j<n){
     
        p = p->next;
        ++j;
    }
    if(!(p->next)||j>n){
     
        return ERROR;
    }
    q = p->next;
    p->next = q->next;
    free(q);
    return OK;
}
//插入
status InsertList(LinkList *L,int n,datatype x){
     
    int i=1;
    LinkList p,q;
    p = *L;
    while(p->next&&i<n){
     
        p = p->next;
        ++i;
    }
    if(!(p->next)||i>n){
     
        return ERROR;
    }
    q = (LinkList)malloc(sizeof(Node));
    q->next = p->next;
    p->next = q;
    return OK;
}
int main(){
     
    LinkList L;
    initlist(&L);
    int length;
    CreateListHeader(&L,10);
    length = ListLength(L);
    printf("(头插法)插入的长度:%d\n",length);
    ClearList(&L);
    length = ListLength(L);
    printf("置空后的长度:%d\n",length);
    CreateListTail(&L,10);
    length = ListLength(L);
    printf("(尾插法)插入的长度:%d\n",length);

    //查询
    datatype num;
    GetElem(L,5,&num);
    printf("查询到的数值为:%d\n",num);


    //删除
    DelElem(&L,4);
    length = ListLength(L);
    printf("删除后插入的长度:%d\n",length);


    //插入
    InsertList(&L,4,3);
    length = ListLength(L);
    printf("插入后插入的长度:%d\n",length);
}

你可能感兴趣的:(线性表,数据结构)