赞
踩
树转存广义表
save.c
#include<stdio.h> #include<stdlib.h> #define FNAME "/tmp/out" struct node_st { char data; struct node_st *l,*r; }; static struct node_st *tree = NULL;//把tree提升到全局变量,当前文件 int insert(struct node_st **root,int data) { struct node_st *node; if(*root == NULL) { node = malloc(sizeof(*node)); if(node == NULL) return -1; node->data = data; node->l = NULL; node->r = NULL; *root = node; return 0; } if(data <= (*root)->data) return insert(&(*root)->l,data); else return insert(&(*root)->r,data); } void draw_(struct node_st *root,int level) { int i; if(root == NULL) return ; draw_(root->r,level+1); for(i = 0;i<level;i++) printf(" "); printf("%c\n",root->data); draw_(root->l,level+1); } void draw(struct node_st *root) { draw_(root,0); printf("\n\n"); //getchar();//相当于暂停 } int save_(struct node_st *root,FILE *fp) { fputc('(',fp); /*if error*/ if(root == NULL) { fputc(')',fp); return 0; } fputc(root->data,fp); /*if error*/ save_(root->l,fp); save_(root->r,fp); fputc(')',fp); /*if error*/ return 0; } int save(struct node_st *root,const char *path) { FILE *fp; fp = fopen(path,"w"); if(fp == NULL) return -1; save_(tree,fp); fclose(fp); // 别忘了关闭文件 return 0; } int main() { char arr[] = "cefadjbh"; int i; for(i = 0;i<sizeof(arr)/sizeof(*arr) - 1;i++) { insert(&tree,arr[i]); } draw(tree); save(tree,FNAME); exit(0); }
广义表转成树
load.c
#include<stdio.h> #include<stdlib.h> #define FNAME "/tmp/out" struct node_st { char data; struct node_st *l,*r; }; void draw_(struct node_st *root,int level) { int i; if(root == NULL) return ; draw_(root->r,level+1); for(i = 0;i<level;i++) printf(" "); printf("%c\n",root->data); draw_(root->l,level+1); } void draw(struct node_st *root) { draw_(root,0); printf("\n\n"); //getchar();//相当于暂停 } struct node_st *load_(FILE *fp) { int c; struct node_st *root; c = fgetc(fp); if(c != '(') { fprintf(stderr,"fgetc():error.\n"); exit(1); } c = fgetc(fp); if(c == ')') return NULL; root = malloc(sizeof(*root)); if(root == NULL) exit(1); root->data = c; root->l = load_(fp); root->r = load_(fp); fgetc(fp); /*if error */ return root; } load(const char *path) { FILE *fp; struct node_st *root; fp = fopen(path,"r"); if(fp == NULL) return NULL; root = load_(fp); fclose(fp); return root; } int main() { struct node_st *root; root = load(FNAME); draw(root); exit(0); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。