c - 队列卡在循环中
问题描述
我在 C 中实现了队列,如下所示。但它陷入了循环。如果我从中删除free()
,deQueue()
那么它工作正常。这种行为的原因是什么。
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
struct item{
int value;
struct item* next;
};
struct item *front = NULL, *rear = NULL;
bool isEmpty(){
return (front == NULL);
}
bool isFull(){
return false;
}
bool enQueue( int value ) {
struct item *temp = (struct item*) malloc( sizeof( struct item ) );
if( temp == NULL ) {
return false;
}
temp->value = value;
temp->next = NULL;
if( front == NULL ) {
printf("Front is NULL\n");
front = temp;
}
if( rear == NULL ) {
printf("Rear is NULL\n");
rear = temp;
} else {
printf("Rear Value %d \n", rear->value );
rear->next = temp;
rear = rear->next;
printf("Rear Value %d \n", rear->value );
}
return true;
}
struct item* deQueue() {
struct item *temp = front;
front = front->next;
return temp;
}
struct item* getFront(){
return front;
}
struct item* getRear(){
return rear;
}
void display(){
struct item* temp = front;
printf("\n[ ");
while( temp ){
printf("%d, ", temp->value);
temp = temp->next;
}
printf("]\n");
}
int main(){
enQueue(1);
display();
free(deQueue());
display();
enQueue(2);
display();
return 0;
}
解决方案
deQueue
更新front
但没有rear
。后者在项目从其下方销毁后留下一个悬空指针。
推荐阅读
- c# - 如何将内连接与 Lambda 表达式一起使用?
- c++ - 在带有 ReSharper 的 VS 中使用 glm::vec3 时出现“不完整类型”警告
- php - 只返回最高的设备维护id
- reactjs - 我将如何规范这个嵌套的减速器案例?
- react-native - 我在反应原生中构建 APK 时遇到了这个错误
- vuetify.js - 如何解决 NuxtJS 和 Vuetify 2.0 之间的 scss 冲突
- typescript - 如何为 Typescript 使用 socket.IO 客户端类型定义?
- r - 如何在 ggplot 2 主题中正确设置线条大小?
- swiftui - 错误不能在属性初始化程序中使用实例成员“xxx”
- reactjs - 需要帮助构建反应表的逻辑