程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 樹的存儲-樹的遍歷與計數中運用隊列來實現

樹的存儲-樹的遍歷與計數中運用隊列來實現

編輯:編程綜合問答
樹的遍歷與計數中運用隊列來實現

#include
#include
#include
#include
#define MAX_TREE_SIZE 100
#define TElemType int
#define QElemType int
#define Status int
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef struct BiTNode//結點結構
{
QElemType data;
int parent;//雙親位置域
}PTNode;

typedef struct{//樹結構
PTNode node[MAX_TREE_SIZE];
int n;//根的位置和結點數
char r;
}PTree;

typedef struct{//隊列的鏈式存儲
TElemType data;
struct *next;
}QNode,*QueuePtr;

typedef struct{
QueuePtr front;//隊頭指針
QueuePtr rear;//隊尾指針
}LinkQueue;

Status InitQueue(LinkQueue Q)//構造一個空隊列
{
Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
if(!Q.front)exit(OVERFLOW);
Q.front->next=NULL;
return OK;
}

Status EnQueue(LinkQueue Q,PTree qq){//入隊
QNode *pp;
pp=(QueuePtr)malloc(sizeof(QNode ));
if(!pp) exit(OVERFLOW);
pp->data=qq.r ;
pp->next=NULL;
Q.rear ->next =pp->next;
Q.rear =pp;
return OK;
}

Status DeQueue(LinkQueue Q,PTree qq){//出隊
QNode *pp;
if(Q.front ==Q.rear ) return ERROR;
Q.front->next=pp->next ;
qq.r =pp->data;
Q.front->next =pp->next ;
if(Q.rear ==pp) Q.rear =Q.front ;
free(pp);
return OK;
}

Status QueueEmpty(LinkQueue Q){
if(Q.rear ==Q.front ) return OK;
else return ERROR;
}

void ClearTree(PTree *T)//構造空樹
{
T->n=0;
}

void CreateTree(PTree T)//構造樹
{
LinkQueue Q;
PTree p,qq;
int i,j,l;
// qq=(PTree )malloc(sizeof(PTNode ));
char c[MAX_TREE_SIZE];/
臨時存放孩子結點數組 /
InitQueue(Q);/
初始化隊列 /
printf("請輸入根結點(字符型,空格為空):");
scanf("%c%*c",&T->node[0].data);/
根結點序號為0,%*c吃掉回車符 /
if(!T->node[0].data)/
非空樹 /
{
T->node[0].parent=-1;/
根結點無雙親 /
qq.r=T->node[0].data;
qq.n=0;
EnQueue(Q,qq);/
入隊此結點 /
while(i<MAX_TREE_SIZE&&QueueEmpty(Q))/
數組未滿且隊不空 /
{
DeQueue(Q,qq); /
出隊一個結點 /
printf("請按長幼順序輸入結點%c的所有孩子: ",qq.r);
gets(c);
l=strlen(c);
for(j=0;j {
T->node[i].data=c[j];
T->node[i].parent=qq.n;
p.r=c[j];
p.n=i;
EnQueue(Q,p); /
入隊此結點 /
i++;
}
}
if(i>MAX_TREE_SIZE)
{
printf("結點數超過數組容量\n");
exit(OVERFLOW);
}
T->n=i;
}
else
T->n=0;
}
//===== 判斷樹是否為空 =====
//
//Status TreeEmpty(PTree *T)
//{ /
初始條件:樹T存在。操作結果:若T為空樹,則返回TRUE,否則返回FALSE */
// return T->n==0;
//}
void main(){
PTree *T1;
T1=(PTree *)malloc(sizeof(PTNode ));
ClearTree(T1);
CreateTree(T1);
}
只寫了這麼一點,運行起有錯,,求破,,

最佳回答:


雖然沒說清楚出的是什麼類型的錯,但是用malloc()動態申請的內存空間使用之前最好用memset()初始化一下,不然程序容易崩潰。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved