通過連結串列實現的簡易通訊錄
阿新 • • 發佈:2018-12-30
學習內容:連結串列通訊錄
#ifndef _LINKLIST_H #define _LINKLIST_H #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 1000 #define FAILURE 10000 #define SUCCESS 10001 #define TRUE 10002 #define FALSE 10003 struct node { char name[100]; int age; struct node *next; }; typedef struct node Node; #endif int LinkInit(Node **l) //初始化 { *l=(Node *)malloc(sizeof(Node)*1); if(NULL == *l) { return FAILURE; } (*l)->next=NULL; return SUCCESS; } int LinkInsert(Node *l) { Node *p=l; char flag = 'y'; if(NULL == l) { return FAILURE; } while(flag == 'y') { Node *q=(Node *)malloc(sizeof(Node)*1); //要插入的 printf("Please input name and age:"); scanf("%s%d",q->name,&q->age); q->next=NULL; p->next=q; p=q; getchar(); printf("finish?(y/n)"); scanf("%c",&flag); } } int LinkShow(Node *l) { if(NULL == l) { return FAILURE; } Node *q = l; while(q->next) { q=q->next; printf("name:%s age:%d\n",q->name,q->age); } getchar(); getchar(); return SUCCESS; } int LinkFind(Node *l) { if(NULL == l ) { return FAILURE; } char *p; p =(char *)malloc(sizeof(char)*32); printf("Please input the name you want to find:"); scanf("%s",p); Node *q = l; int i; while(q != NULL) { if(strcmp(q->name,p) == 0) { printf("name:%s age:%d",q->name,q->age); break; } else { q=q->next; } } if(!q) { return FAILURE; } return SUCCESS; } int LinkDelete(Node *l) { if(NULL == l) { return FAILURE; } Node *q = l; Node *m = l; Node *t; int n=0; int k=1; char *p; p = (char*)malloc(sizeof(char)*32); printf("Please input the name you want to delete:"); scanf("%s",p); while(l->next != NULL) { q = q->next; n++; if(strcmp(q->name,p) == 0) { t = q; break; } } while (k < n && m != NULL) { m = m->next; k++; } m->next=t->next; free(p); } int LinkCorrect(Node *l) { if(NULL == l ) { return FAILURE; } char *p; p =(char *)malloc(sizeof(char)*32); printf("Please input the name you want to change:"); scanf("%s",p); Node *q = l; while(q != NULL) { if(strcmp(q->name,p) == 0) { printf("Please input the name after change:"); scanf("%s",q->name); printf("Please input the age after change:"); scanf("%d",&q->age); break; } else { q=q->next; } } if(!q) { return FAILURE; } return SUCCESS; } void welcome() { printf("\t\t\033[46m*************************\n"); printf("\t\t*********Welcome!********\n"); printf("\t\t*************************\n"); } void menu() { system("clear"); printf("\n"); printf("\t\t************************\n"); printf("\t\t1.新增 2.檢視 \n"); printf("\t\t3.查詢 4.刪除 \n"); printf("\t\t5.修改 6.返回 \n"); printf("\t\t************************\n"); } int main() { Node *first = NULL; int choice; welcome(); LinkInit(&first); while(1) { menu(); scanf("%d",&choice); switch(choice) { case 1:LinkInsert(first); break; case 2:LinkShow(first); break; case 3:LinkFind(first); break; case 4:LinkDelete(first); break; case 5:LinkCorrect(first); break; case 6:exit(0); break; } } return 0; }