C 单链表

来源:互联网 发布:淘宝达人帐号简介范例 编辑:程序博客网 时间:2024/05/18 00:07
#pragma once//定义一个结构体(.h文件)typedef struct _NODE{    int count;    char name[8];    struct _NODE* next;}NODE;int _insert(const char* name, int count);int _insert2(const char* name, int count, int con);int _remove(const char* name);NODE* _find(const char* name);int _modify(const char* name, const char* NewName);void _show()
#include "LinkList.h"#include <stdlib.h>#include <string.h>//定义一个链表NODE* list=NULL;//插入到链表的最后面int _insert(const char* name, int count){    NODE* node = (NODE*)malloc(sizeof(NODE));    memset(node,0x00,sizeof(NODE));    strcpy(node->name,name);    memcpy(&node->count,&count,sizeof(count));    node->next = NULL;    if (list==NULL)    {        list = node;        return 1;    }    for (NODE* p = list;; p=p->next)    {        if (p->next == NULL)        {            p->next = node;            return 1;        }    }    return 0;}//插入到链表的指定位置(con)int _insert2(const char* name, int count, int con){    NODE* node = (NODE*)malloc(sizeof(NODE));    memset(node, 0x00, sizeof(NODE));    strcpy(node->name, name);    memcpy(&node->count, &count, sizeof(count));    node->next = NULL;    if (con == 0)    {        NODE* p = list;        node->next = p;        list = node;        return 1;    }    int c = 1;    for (NODE* p = list;p!=NULL; p = p->next)    {        if (c==con)        {            node->next = p->next;            p->next = node;            return 1;        }    }    free(node);    return 0;}//根据name删除链表中第一个name的节点(name)int _remove(const char* name){    NODE* p = list;    if (0 == strcmp(p->name, name))    {        NODE* pp = p->next;        list = pp;        free(p);        return 1;    }    while (p!=NULL)    {        if (0==strcmp(p->next->name,name))        {            NODE* pp = p->next;            p->next = p->next->next;            free(pp);            return 1;        }        p = p->next;    }    return 0;}//根据name查找第一个节点(name)NODE* _find(const char* name){    NODE* p = list;    while (p != NULL)    {        if (0 == strcmp(p->name, name))        {            return p;        }        p = p->next;    }    return NULL;}//根据name修改成NewName(name,NewName)int _modify(const char* name, const char* NewName){    NODE* p = list;    int i = 0;//表示修改了几个值    while (p != NULL)    {        if (0 == strcmp(p->name, name))        {            strcpy(p->name, NewName);            i++;        }        p = p->next;    }    return i;}