作者skiusan (天空无限)
看板Programming
标题[问题] C语言用Linked List 建BST
时间Fri Dec 30 23:33:17 2011
写程式时遇到一些问题想请教各位前辈:
1) 产生新的节点(temp)时 有时候会让程式异常终止(当掉)
而且常在第4、5个新节点就当掉 是为什麽呢 不太可能是记忆体不足吧?
2) 建树完成後 第二个新节点(即Root的下一个)的右子点 每次走访到它就会当掉
而把struct node结构里的lchild, rchild顺序交换 变成左子点走访时会当掉
以下是我的程式码
烦请各位给些建议 谢谢
---
typedef struct node *ptrn;
struct node
{
int elem;
ptrn lchild;
ptrn rchild;
};
void inorder(ptrn tree);
int main()
{
int i;
ptrn set,temp,start;
//Construct a Root
temp = (ptrn)malloc(sizeof(ptrn));
start = temp;
scanf("%d",&i);
temp -> elem = i;
temp -> lchild = NULL;
temp -> rchild = NULL;
printf("ROOT saved\n");
while(1)
{
scanf("%d",&i);
if(i==-1) break;
temp = (ptrn)malloc(sizeof(ptrn));
if(temp == NULL)
{
printf("malloc fail.\n");
temp = (ptrn)malloc(sizeof(ptrn));
}
temp->elem = i;
temp->lchild = NULL;
temp->rchild = NULL;
set = start;
while(1)
{
while(temp->elem > set->elem)
{
if(set->rchild==NULL)
{
set->rchild = temp;
printf("RC saved\n");
break;
}
set = set->rchild;
}
while(temp->elem <= set->elem)
{
if(set->lchild==NULL)
{
set->lchild = temp;
printf("LC saved\n");
break;
}
set = set->lchild;
}
break;
}
}
inorder(start);
system("pause");
}
void inorder(ptrn tree)
{
if(tree!=NULL)
{
inorder(tree->rchild);
inorder(tree->lchild);
printf("%d\n",tree->elem);
}
else printf("NULL Node\n");
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 203.217.108.247
1F:→ firejox:就你的问题 可能是没有连好吧... 123.240.128.52 12/30 23:47
2F:→ firejox:拿一张纸和笔模拟一下过程 看有没有遗漏的 123.240.128.52 12/30 23:47
3F:→ firejox:地方... 123.240.128.52 12/30 23:48
4F:→ skiusan:第二点有这个可能 但是第一点呢203.217.108.247 12/31 00:13
5F:推 chchwy:当掉就是走错 连错了 220.134.128.54 12/31 01:06
6F:→ felixtung:1. malloc()失败不该无止尽做下去。 111.251.207.65 12/31 08:37
7F:→ felixtung:2.Insert node的while回圈错了,再仔细 111.251.207.65 12/31 08:38
8F:→ felixtung:想一下吧!^^ 111.251.207.65 12/31 08:38
9F:→ felixtung:PS:你的insert node也可以用recursive 111.251.207.65 12/31 08:40
10F:→ felixtung:call来实现,会比较简洁!^^ 111.251.207.65 12/31 08:40
11F:→ felixtung:抱歉看错!malloc()失败没有无止尽做下 111.251.207.65 12/31 09:10
12F:→ felixtung:去。 111.251.207.65 12/31 09:11
13F:→ felixtung:只是再做一次也不保证就会成功了!^^ 111.251.207.65 12/31 09:11
14F:→ firejox:insert只要一层while就好... 123.240.128.52 12/31 15:10
15F:→ firejox:假如malloc失败还要剥削电脑= = 123.240.128.52 12/31 15:13
16F:→ skiusan:谢谢两位 继续尝试中203.217.108.247 01/01 17:19