单向链表 增 删 改 查

#include #include typedef struct node { int num; node* next; } NODE; int lenght = -1; //线性表的链式结构的长度/* 创建节点 */ NODE* create_node(int num) { NODE* n = (NODE*) malloc(sizeof(NODE)); n->num = num; n->next = NULL; lenght++; return n; }/* 插入一个结点到某个数字的后面 return 插入是否成功 */ int insert_node(NODE* head, int how, int num) { NODE* p = head->next; while (p != NULL) { if (p->num == how) { NODE* z = p->next; p->next = create_node(num); p->next->next = z; return 1; } p = p->next; } return 0; }/* 删除一个结点 */ int delete_node(NODE* head, int how) { NODE* p = head->next; NODE* last = head; while (p != NULL) { if (p->num == how) { last->next = p->next; free(p); p = NULL; lenght--; return 1; } p = p->next; last = last->next; } return 0; }/* 修改一个结点 */ void update_node(NODE* head, int how, int num) { NODE* p = head->next; while (p != NULL) { if (p->num == how) { p->num = num; return; } p = p->next; } printf("该元素不存在!\n"); }/* 查询一个节点 */ void search_node(NODE* head, int how) { NODE* p = head->next; while (p != NULL) { if (how == p->num) { printf("查询到 %d\n", p->num); return; } p = p->next; } printf("该元素不存在!\n"); }void print_list(NODE* head) {//线性表的链式结构的遍历 NODE* p = head; while (p != NULL) { printf("%d ", p->num); p = p->next; } printf("\n\n"); } int main() { NODE* headNode = create_node(-1); //创建头结点 NODE* p = headNode; for (int i = 0; i < 10; i++) { p->next = create_node(i); if (headNode->next == NULL) { printf("NULL"); } p = p->next; } printf("线性表的链式结构的长度 = %d\n", lenght); print_list(headNode->next); printf("--插入数据:100\n"); insert_node(headNode, 4, 100); //在数字4的后面插入100 printf("线性表的链式结构的长度 = %d\n", lenght); print_list(headNode->next); printf("--删除数据:0\n"); delete_node(headNode, 0); //删除数字为0的节点 printf("线性表的链式结构的长度 = %d\n", lenght); print_list(headNode->next); printf("--修改数据:1\n"); update_node(headNode, 1, 111); //修改数字1为111 printf("线性表的链式结构的长度 = %d\n", lenght); print_list(headNode->next); printf("--查询数据:1000\n"); search_node(headNode, 1000); //查询1000是否存在于链表当中 return 0; }



【单向链表 增 删 改 查】

    推荐阅读