昨日写数据结构,写到树的遍历的时候卡了壳.看了几遍源码也没弄明白为何不对.最后发现是malloc和calloc的区别没弄明白导致的.
以下是遍历树前进行的准备.
//
// Created by shangkejie on 2020/4/13.
//
#ifndef LEARNTREE_MYTREE_H
#define LEARNTREE_MYTREE_H
#include
#include
#include
typedef char binTreeElemType;
typedef struct binTree{
binTreeElemType data;//数据
struct binTree *lchild;//当前节点的左孩子
struct binTree *rchild;//当前节点的右孩子
}binTree,*BinTree;
typedef struct tag{
BinTree p;
struct tag *next;
}tag,*ptag;
//栈的数据结构
#define MaxSize 50
typedef BinTree ElemType;
typedef struct {
ElemType data[MaxSize];
int top;
}myStack;
void initStack(myStack *stack);
bool stackEmpty(myStack *stack);
bool stackPush(myStack *stack,ElemType x);
bool stackPop(myStack *stack,ElemType *x);
bool stackGetTop(myStack *stack,ElemType *x);
//队列相关数据结构
typedef struct linkNode{
ElemType data;
struct linkNode *linkNext;
}linkNode;
typedef struct {
linkNode *front,*rear;
}linkQueue;
void initQueue(linkQueue *linkQueue);
bool queueEmpty(linkQueue linkQueue);
void enQueue(linkQueue *linkQueue,ElemType x);
bool delQueue(linkQueue *linkQueue,ElemType *x);
#endif //LEARNTREE_MYTREE_H
分析一下源码
#include "myTree.h"
void PrePrint(BinTree pTree);
int main() {
BinTree treeNew;
int i,j,pos;
char ch;
BinTree tree=NULL;//树根
ptag pHead=NULL,pTail=NULL,listPNew,pCur;
//abcdefghij
while (scanf("%c",&ch)!=EOF){
if (ch=='\n'){
break;
}
treeNew=(BinTree)malloc(sizeof(struct binTree));
treeNew->data=ch;
listPNew=(ptag)malloc(sizeof(struct tag));
listPNew->p=treeNew;
if (NULL==tree){
tree=treeNew;
pHead=listPNew;
pTail=listPNew;
pCur=listPNew;
continue;
} else{
pTail->next=listPNew;
pTail=listPNew;
}
if (NULL==pCur->p->lchild){//左子树为空
pCur->p->lchild=treeNew;
} else if (NULL==pCur->p->rchild){//右子树为空
pCur->p->rchild=treeNew;
pCur=pCur->next;
}
}
printf("--------PreOrder--------\n");
PrePrint(tree);
printf("\n--------INOrder--------\n");
printf("\n--------POSTOrder--------\n");
printf("\n--------PreOrder--------\n");
return 0;
}
void PrePrint(BinTree pTree) {
if (pTree!=NULL){
printf("%c",pTree->data);
//putchar(pTree->data);
PrePrint(pTree->lchild);
PrePrint(pTree->rchild);
}
}
记过Debug,发现了错误原因,此处直接跳过了.
if (NULL==pCur->p->lchild){//左子树为空
pCur->p->lchild=treeNew;
为什么会跳过呢?不应该是NULL吗?
百思不得姐,然后又一字不差的对了一遍源码?发现是malloc的原因.
malloc初始化的空间是带有数据的,只不过数据的随机的.称之为"脏数据"
将malloc改为calloc以后.,问题迎刃而解.
treeNew=(BinTree)calloc(1,sizeof(struct binTree));
treeNew->data=ch;
listPNew=(ptag)calloc(1,sizeof(struct tag));
listPNew->p=treeNew;
calloc在初始数据的时候,会将空间初始为默认值,假如是int型的数据,就初始化为0,假如是指针就初始化为NULL
如此以来,便知道了malloc和calloc的不同.
malloc初始化的空间是带有数据的,只不过数据的随机的.称之为"脏数据"
calloc在初始数据的时候,会将空间初始为默认值,假如是int型的数据,就初始化为0,假如是指针就初始化为NULL