链表的实战讲解(综合以前的基础)

最后更新于:2022-04-01 09:43:10

这是前面我讲得算法与数据结构中链表的综合,如果这里不明白请看前面的基础知识:[链接地址](http://blog.csdn.net/qq_21792169/article/details/49302909)。 ~~~ #include <stdio.h> #include <stdlib.h> #include <string.h> /* 定义一个结构体 */ typedef struct NAME{ char *name; struct NAME *pre; struct NAME *next; }T_Name, *PT_Name; static PT_Name   g_ptNameHead;    /* 定义链表头 */ void add_name(PT_Name ptNew) { PT_Name ptCur; if (g_ptNameHead == NULL) { g_ptNameHead = ptNew; } else { ptCur = g_ptNameHead; while (ptCur->next) { ptCur = ptCur->next; } ptCur->next = ptNew; ptNew->pre  = ptCur; } } void del_name(PT_Name ptDel) { PT_Name ptCur; PT_Name ptPre; PT_Name ptNext; if (g_ptNameHead == ptDel)   /* 如果链表头等于当前删除的链表 */ { g_ptNameHead = ptDel->next; /* 释放 */ return; } else { ptCur = g_ptNameHead->next; while (ptCur) { if (ptCur == ptDel) { /* 从链表中删除 */ ptPre  = ptCur->pre; ptNext = ptCur->next; ptPre->next = ptNext; if (ptNext) { ptNext->pre = ptPre; } break; } else { ptCur = ptCur->next; } } } free(ptDel->name); free(ptDel); } void add_one_name() { PT_Name ptNew; char *str; char name[128]; printf("enter the name:"); scanf("%s", name); str  = malloc(strlen(name) + 1);   /* name是一个局部变量,用来存放名字,当这个函数结束的时候,该内存就得释放,所以我们得单独分配一块内来存放这个name ,下面还得用malloc来分配一个结构体大的内存空间,记住我们定义结构体的时候不能添加static,因为定义结构提示不会分配内存空间的,他定义的只是这种类型,所以我们增加的时候一定要记得分配内存*/ strcpy(str, name); ptNew = malloc(sizeof(T_Name)); ptNew->name = str; ptNew->pre  = NULL; ptNew->next = NULL; add_name(ptNew); } PT_Name get_name(char *name) { PT_Name ptCur; if (g_ptNameHead == NULL) { return NULL; } else { ptCur = g_ptNameHead; do { if (strcmp(ptCur->name, name) == 0) return ptCur; else ptCur = ptCur->next; }while (ptCur); } return NUL; } void del_one_name() { PT_Name ptFind; char name[128]; printf("enter the name:"); scanf("%s", name); ptFind = get_name(name); if (ptFind == NULL) { printf("do not have this name\n"); return ; } del_name(ptFind); } void list_all_name(void) { PT_Name ptCur; int i = 0; ptCur = g_ptNameHead; while (ptCur) { printf("%02d : %s\n", i++, ptCur->name); ptCur = ptCur->next; } } int main(int argc, char **argv) { char c; while (1) { printf("<l> List all the names\n"); printf("<a> add one name\n"); printf("<d> del one name\n"); printf("<x> exit\n"); printf("Enter the choise: "); c = getchar(); switch (c) { case 'l': { list_all_name(); break; } case 'a': { add_one_name(); break; } case 'd': { del_one_name(); break; } case 'x': { return 0; break; } default: { break; } } } return 0; } ~~~
';