设为首页 加入收藏

TOP

C语言随机函数(四)
2013-11-29 16:13:29 来源: 作者: 【 】 浏览:1102
Tags:语言 随机 函数

 

  //初始化一棵树

  tree init_tree(int key)

  {

  struct node * t;

  t=(tree)malloc(sizeof(struct node));

  if(t==NULL)

  return NULL;

  t->key=key;

  t->parent=t->left=t->right=NULL;

  return t;

  }

  //释放资源

  void fini_tree(tree T)

  {

  if(T!=NULL){

  fini_tree(T->left);

  fini_tree(T->right);

  printf("free node(%d,%s) now\n",T->key,T->data);

  free(T);

  }

  }

  //测试程序

  int main()

  {

  tree myTree=init_tree(256);

  if(myTree==NULL)

  return 1;

  strcpy(myTree->data,"JJDiaries");

  struct record{

  int key;

  char word[WORDLEN];

  };

  struct record records[]={ {2,"Viidiot"},

  {4,"linux-code"},

  {123,"google"},

  {345,"baidu"},

  {543,"nsfocus"}

  };

  int i;

  struct node *tmp;

  for(i=0;i<5;++i){

  tmp=(tree)malloc(sizeof(struct node));

  if(tmp==NULL)

  continue;

  tmp->key=records[i].key;

  strcpy(tmp->data,records[i].word);

  tmp->left=tmp->right=tmp->parent=NULL;

  tree_insert(&myTree,tmp);

  }

  inorder_tree_walk(myTree);

  struct node *del;

  del=tree_delete(&myTree,tree_search(myTree,345));

  printf("Delete node(%d,%s)\n",del->key,del->data);

  free(del);

  inorder_tree_walk(myTree);

  fini_tree(myTree);

  }

  //程序运行结果:

  jjdiaries@ubuntu>./search_tree

  key:2   words:Viidiot

  key:4   words:linux-code

  key:123   words:google

  key:256   words:JJDiaries

  key:345   words:baidu

  key:543   words:nsfocus

  Delete node(345,baidu)

  key:2   words:Viidiot

  key:4   words:linux-code

  key:123   words:google

  key:256   words:JJDiaries

  key:543   words:nsfocus

  free node(123,google) now

  free node(4,linux-code) now

  free node(2,Viidiot) now

  free node(543,nsfocus) now

  free node(256,JJDiaries) now

        

首页 上一页 1 2 3 4 5 6 7 下一页 尾页 4/11/11
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇二叉查找树 下一篇在C语言下用google protobuf

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: