我编写了使用队列遍历树的代码,但是下面的去队列函数会产生错误,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;
}
发布于 2016-02-15 23:51:13
while循环的条件是:
while (tmp != NULL) {
因此,只有当dequeue
在这里返回NULL
时,它才会终止:
tmp = dequeue();
但是,在查看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;
...
https://stackoverflow.com/questions/35420750
复制相似问题