链表的实现

来源:互联网 发布:erlang python 编辑:程序博客网 时间:2024/06/07 02:55

链表的实现

#include <stdio.h>#include <stdlib.h>#include <stdbool.h>

//List链表typedef int ElementType;typedef struct _node{    ElementType data;    struct _node *next;}Node, * NodePointer;typedef struct _list{    Node *header;//    int capacity;//总容量//    int size;//已存数据大小}List, * ListPointer;ListPointer initialize();void destroy(ListPointer listp);void makeEmpty(ListPointer listp);void insert(ListPointer listp, NodePointer nodep);void traverse(ListPointer listp);NodePointer createNodeWithElement(ElementType data){    NodePointer p = malloc(sizeof(Node));    p->data = data;    return p;}ListPointer initialize(){    ListPointer listp = malloc(sizeof(List));        //NodePointer headerNode = malloc(sizeof(Node));    NodePointer headerNode = calloc(1, sizeof(Node));    headerNode->data = 0;    headerNode->next = NULL;    listp->header = headerNode;        //listp->header = NULL;        return listp;}void traverse(ListPointer listp){    NodePointer next = listp->header;    if (!next) {        printf("空\n");    }    while (next) {        printf("the element is %d\n", next->data);        next = next->next;    }}void insert(ListPointer listp, NodePointer nodep){    NodePointer nextP = listp->header;    NodePointer tailNodeP = NULL;    while (nextP) {        if (!nextP->next) {            tailNodeP = nextP;        }        nextP = nextP->next;    }        tailNodeP->next = nodep;}NodePointer findElement(ListPointer listp, ElementType data){    NodePointer nextp = listp->header;    while (nextp) {        if (nextp->data == data) {            return nextp;        }        nextp = nextp->next;    }    return NULL;}bool deleteElement(ListPointer listp, ElementType data){    NodePointer nextp = listp->header;    NodePointer previous = NULL;    bool isFind = false;    while (nextp) {        if (nextp->data == data) {            isFind = true;            break;        }        previous = nextp;        nextp = nextp->next;    }        if (isFind && previous) {        NodePointer next = nextp->next;        if (next) {            previous->next = next;            free(nextp);        }else{            previous->next = NULL;            free(nextp);        }    }    return true;}void testInfoMessage(){    ListPointer listp = initialize();    traverse(listp);        NodePointer nodep = createNodeWithElement(12);    insert(listp, nodep);    traverse(listp);        nodep = createNodeWithElement(13);    insert(listp, nodep);    traverse(listp);        nodep = createNodeWithElement(23);    insert(listp, nodep);    traverse(listp);        nodep = createNodeWithElement(33);    insert(listp, nodep);    traverse(listp);        //deleteElement(listp, 13);        deleteElement(listp, 33);        traverse(listp);}


原创粉丝点击