C语言实现二叉链表:添加、查找、删除节点
#include<stdio.h> #include<stdlib.h> #include<string.h>
//定义二叉链表节点 typedef struct node{ struct node *lchild,*rchild; char code[10]; char name[20]; }Node;
//创造节点 Node* createnode(char* code, char* name){ Node* newnode=(Node*)malloc(sizeof(Node)); strcpy(newnode->code, code); strcpy(newnode->name, name); newnode->lchild=NULL; newnode->rchild=NULL; return newnode; }
//插入结点 Node* insertNode(Node* root, char* code, char* name, char* parentcode){ if (root == NULL){ return NULL; } if (strcmp(root->code, parentcode) == 0){ Node* newnode = createnode(code, name); if (root->lchild == NULL){ root->lchild = newnode; } else if (root->rchild == NULL){ root->rchild = newnode; } } else { root->lchild = insertNode(root->lchild, code, name, parentcode); root->rchild = insertNode(root->rchild, code, name, parentcode); } return root; }
//递归实现层次输出 void cenciprint(Node* root){ if (root == NULL){ return; } printf('%s\n', root->name); if (root->lchild != NULL){ printf(' '); cenciprint(root->lchild); } if (root->rchild != NULL){ cenciprint(root->rchild); } }
//递归查找最低一级缺陷名 void find(Node* root){ if (root == NULL){ return; } if (root->lchild == NULL){ printf('%s ', root->name); } find(root->lchild); find(root->rchild); }
//递归输出所有节点名 void printall(Node* root){ if (root == NULL){ return; } printf('%s ', root->name); printall(root->lchild); printall(root->rchild); }
//递归删除节点 Node* deletenode(Node* root, char* code){ if (root == NULL){ return NULL; } if (strcmp(root->code, code) == 0){ Node* left = root->lchild; Node* right = root->rchild; free(root); if (left == NULL){ return right; } if (right == NULL){ return left; } Node* cur = left; while (cur->rchild != NULL){ cur = cur->rchild; } cur->rchild = right; return left; } else { root->lchild = deletenode(root->lchild, code); root->rchild = deletenode(root->rchild, code); return root; } }
int main(){ // 初始化创建二叉链表 Node* root = createnode('SBQX01', '设备缺陷'); root = insertNode(root, 'YLQX01', '一类缺陷', 'SBQX01'); root = insertNode(root, 'ELQX02', '二类缺陷', 'SBQX01'); root = insertNode(root, 'WDYC01', '发电机线圈温度异常', 'YLQX01'); root = insertNode(root, 'DJYY01', '煤机清扫电机异音', 'ELQX02');
// 按层次输出
printf('按层次所属关系输出:\n');
cenciprint(root);
// 查找并输出所有最低一级缺陷名
printf('所有最低一级缺陷名:\n');
find(root);
printf('\n');
// 输出所有分类名
printf('所有分类名:\n');
printall(root);
printf('\n');
// 在“一类缺陷”下插入“电动阀电气故障 ”,“二类缺陷”下插入””
root = insertNode(root, 'DDFDQGZ01', '电动阀电气故障', 'YLQX01');
root = insertNode(root, 'JDBHZZ01', '继电保护装置', 'ELQX02');
root = insertNode(root, 'SFJJSZD01', '送风机绝缘值低', 'ELQX02');
// 按层次输出
printf('插入节点后按层次所属关系输出:\n');
cenciprint(root);
// 删除某一分类及其包含的所有缺陷
root = deletenode(root, 'ELQX02');
// 按层次输出
printf('删除二类缺陷后按层次所属关系输出:\n');
cenciprint(root);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/oYjB 著作权归作者所有。请勿转载和采集!