数据结构 C语言实现 线性表的链式实现

来源:互联网 发布:数据对门店的重要性 编辑:程序博客网 时间:2024/04/26 21:41

本节定义的两个类型LNodeType和LinkListType.
LNodeType 为结点,LinkListType为指向LNodeType的指针。
难点在于L_CreatList的参数Lhead为返回数据,类型为指向LNodeType指针的指针(双重指针)。

#include <stdio.h>#include <stdlib.h>#include "define.h"typedef int ElemType;typedef struct LNode LNodeType;typedef struct LNode *LinkListType;struct LNode {    ElemType data;    struct LNode *next;};Status L_GetElem(LinkListType Lhead, int i, ElemType *e){    LNodeType *p;    int j = 1;    p = Lhead -> next;    while ( p && j < i ){        p = p->next;        ++j;    }    if( !p || j > i )        return ERROR;    *e = p->data;    return OK;}Status L_ListInsert(LinkListType Lhead, int i, ElemType e){    LinkListType p;    int j = 0;    p = Lhead;    while ( p && j < i - 1 ) {        p = p->next;        ++j;    }    if ( !p || j > i )         return ERROR;    LinkListType s;    s = (LinkListType ) malloc ( sizeof(LNodeType));    s->data = e;    s->next = p->next;    p->next = s;    return OK;}Status L_ListDelete(LinkListType L, int i, ElemType *e){    LinkListType p, q;    int j;    p = L;    j = 0;    while(p->next && j < i-1 ) {        p = p->next;        ++j;    }    if ( !(p->next) || j > i-1)        return ERROR;    q = p -> next;    p->next = q->next;    *e = q->data;    free(q);    return OK;}/* * 逆序创建n个数据的链表 */void L_CreateList( LinkListType *Lhead, int n){    LinkListType p, L;    int i;    L = (LinkListType)malloc(sizeof(LNodeType));    L->next = NULL;    for ( i = n; i > 0; --i){        p = (LinkListType) malloc(sizeof(LNodeType));        scanf("%d",&p->data);//输入数据的类型限制为整形了。        p->next = L->next;        L->next = p;    }    *Lhead = L;}void L_MergeList(LinkListType La, LinkListType Lb, LinkListType *Lc){    LinkListType pa,pb,pc;    pa = La->next;    pb = Lb->next;    *Lc = pc = La;    while (pa && pb) {        if (pa->data <= pb->data){            pc->next = pa;            pc = pa;            pa = pa->next;        }else{            pc->next = pb;            pc = pb;            pb = pb->next;        }    }    pc->next = pa ? pa : pb;    free(Lb);}/* * 以下为随手测试一下 */void printList( LinkListType L ){    if (L->next == NULL){        printf("data is empty");    }    L = L->next;    while (L !=NULL){    printf("%d\n", L->data);    L = L->next;    }}int main(void){    LinkListType L;    L_CreateList(&L, 2);    printf("\n-printList-----\n");    printList(L);    printf("\n--GetElem 1 ----\n");    ElemType e;    L_GetElem(L, 1, &e);    printf("%d\n",e);    L_ListInsert(L, 2, 99);    printf("\n-ListInsert- 2----\n");    printList(L);    printf("\n---ListDelete 1 ---\n");    L_ListDelete(L,1,&e);    printf("e = %d\n", e);    printList(L);    return 0;}
0 0
原创粉丝点击