C 树:使用队列的级别顺序遍历
我写了一些代码,使用queue遍历树,但下面的dequeue函数会产生错误,C 树:使用队列的级别顺序遍历,c,tree,C,Tree,我写了一些代码,使用queue遍历树,但下面的dequeue函数会产生错误,head=p->next有什么问题吗? 我不明白为什么这部分错了 void Levelorder(void) { node *tmp, *p; if (root == NULL) return; tmp = root; printf("The level order is :\n"); while (tmp != NULL) { printf("%d, ", tmp->data); if
head=p->next
有什么问题吗?
我不明白为什么这部分错了
void Levelorder(void) {
node *tmp, *p;
if (root == NULL) return;
tmp = root;
printf("The level order is :\n");
while (tmp != NULL) {
printf("%d, ", tmp->data);
if (tmp->left) {
enqueue(tmp->left);
}
if (tmp->right) {
enqueue(tmp->right);
}
tmp = dequeue();
}
return;
}
void enqueue(node *p) {
if (head == NULL) {
head = p;
}
else {
tail->next = p;
}
tail = p;
p->next = NULL;
tail->next = NULL;
return;
}
node* dequeue(void) {
node *p;
p = head;
head = p->next;
if (head == NULL) {
tail == NULL;
}
return p;
}
while循环的条件是:
while (tmp != NULL) {
因此,只有当dequeue
在此处返回NULL
时,它才会终止:
tmp = dequeue();
但是,在研究出列的实现时,这是不可能发生的:
node* dequeue(void) {
node *p;
p = head;
此处,p
被取消引用:
head = p->next;
if (head == NULL) {
tail == NULL;
}
在这里,p
返回:
return p;
}
要返回NULL
指针并离开while循环,p
必须在这里NULL
。但是,一个NULL
指针将被head=p->next解除引用代码>之前,这将导致分段错误(在C语言中为UB)
如果head
是空指针,则应在出列函数的开头检查,并在这种情况下返回NULL:
node* dequeue(void) {
node *p;
if (!head)
return NULL;
...
谢谢你的hep。但仍然无法理解“头=p->下一步”这句话的含义。“head=p->next”如何延迟包含空指针的p?@Ezerk它不能,这就是程序在该点崩溃的原因。也许你很恼火,因为那时你根本没有产出;这是因为printf()
通常在终端设备上对其输出进行行缓冲。谢谢您的评论。