//头文件 Node.h
#ifndef _Node_ #define _Node_ typedef struct _node { int number; struct _node *next; }Node; #endif // ! _node_
//头文件 List.h
#ifndef _LIST_ #define _LIST_ #include "Node.h" typedef struct _list { Node *head; //Node *tail; }List; #endif // !_LIST_
//头文件 List_OP.h
#ifndef _LIST_OP_ #define _LIST_OP_ #include <stdio.h> #include <stdlib.h> #include "Node.h" #include "List.h" void add_list(List *plist, int num) { //添加链表的节点 Node *last = NULL; last = plist->head; Node *p = (Node *)malloc(sizeof(Node)); p->number = num; p->next = NULL; if (last) { //当last为NULL时,last->next无意义 while (last->next) { last = last->next; } last->next = p; } else { plist->head = p;//最开始时,让p来当头指针 } } void print_list(List list) { //完成输入后打印整串链表 Node *p; for (p = list.head; p; p = p->next) { printf("%d\n", p->number); } } void search_list(List list, int srch) { //查找是否存在所找项 Node *p; int i = 1; int IsFound = 0; for (p = list.head; p; i++,p = p->next) { if (p->number == srch) { printf("Found! Locate at number %d\n", i); IsFound = 1; break; } } if (IsFound == 0) { printf("Not Found!\n"); } } void delet_list(List list, int srch) { //如果找到,删除节点 Node *q, *p; int IsFound = 0; for (q = NULL, p = list.head; p; q = p, p = p->next) { if (p->number == srch) { if (q) { q->next = p->next; } else { list.head->next = p->next; } free(p); IsFound = 1; printf("Delete!\n"); break; } } if (IsFound == 0) { printf("CANNOT DO IT!\n"); } printf("New List:\n"); print_list(list); } #endif // ! _LIST_OP_
//主函数
#include <stdio.h> #include <stdlib.h> #include "Node.h" #include "List.h" #include "List_OP.h" void add_list(List *plist, int num); void print_list(List list); void search_list(List list, int srch); void delet_list(List list, int srch); int main() { int num = 0; List list; list.head = NULL; do { printf("input the number\n"); scanf("%d", &num); if (num != -1) { add_list(&list, num); } } while (num != -1); print_list(list); int srch = 0; //int IsFound = 0; //值作为是否执行删除函数的标志 printf("input a number to search the list\n"); scanf("%d", &srch); search_list(list, srch); delet_list(list, srch); return 0; }