|
发表于 2004-12-5 01:08:08
|
显示全部楼层
这是我修改出的- //stack.h
- #include <stdlib.h>
- /* Store per pointer of bitree */
- typedef void * lkstack_datatype;
- typedef struct lkstack_node * lkstack_pointer;
- struct lkstack_node
- {
- lkstack_datatype data;
- lkstack_pointer next;
- };
- typedef struct
- {
- lkstack_pointer top;
- } lkstack;
- /* functions for lkstack */
- int push_lkstack(lkstack *ls,lkstack_datatype x)
- {
- lkstack_pointer p=(lkstack_pointer)malloc(sizeof(struct lkstack_node));
- p->data=x;
- p->next=ls->top;
- ls->top=p;
- return 1;
- }
- int pop_lkstack(lkstack *ls, lkstack_datatype [color=orange]*x[/color] )
- {
- lkstack_pointer p;
- if(ls->top==NULL) return 0;
- p=ls->top;
- [color=orange]*x=p->data;[/color]
- ls->top=p->next;
- free(p);
- return 1;
- }
- void init_lkstack(lkstack *ls)
- {
- ls->top=NULL;
- }
复制代码- //bitree.c
- #include <stdlib.h>
- #include "stack.h"
- typedef int datatype;
- typedef struct node *pointer;
- struct node
- {
- datatype data;
- pointer lchild,rchild;
- };
- typedef pointer bitree;
- bitree create_bitree (char Pre[],int ps,int pe,char In[],int is,int ie)
- {
- bitree t;
- int i;
- if(ps>pe) return NULL;
- t=(bitree)malloc(sizeof(struct node));
- t->data=Pre[ps];
- i=is;
- while(In[i]!=Pre[ps]) i++;
- t->lchild=create_bitree(Pre,ps+1,ps+i-is,In,is,i-1);
- t->rchild=create_bitree(Pre,ps+i-is+1,pe,In,i+1,ie);
- return t;
- }
- int free_bitree(bitree t)
- {
- if(t->lchild==NULL && t->rchild==NULL) {
- free(t);
- return 1;
- }
- free_bitree(t->lchild);
- free_bitree(t->rchild);
- free(t);
- return 1;
- }
- void list_bitree_rlr(bitree t)
- {
- lkstack mylkstack;
- /* DEBUG start */
- lkstack *debug=&mylkstack;
- /* DEBUG end */
- init_lkstack(&mylkstack);
- [color=orangered] push_lkstack(&mylkstack,NULL);//在栈底放置NULL指针[/color]
- pointer p=t;
- while(p!=NULL){
- printf("%c ",p->data);
- if(p->rchild!=NULL) {
- push_lkstack(&mylkstack,p->rchild);
- }
- if(p->lchild==NULL) {
- pop_lkstack(&mylkstack,(void*)&p);
- continue;
- }
- p=p->lchild;
- }
- }
- main()
- {
- bitree t;
- char Pre[6]="ABDEC";
- char In[6]="DBEAC";
- t=create_bitree(Pre,0,4,In,0,4);
- list_bitree_rlr(t);
- if(free_bitree(t)) printf("ok, the tree is free.\n");
- }
复制代码 |
|