c - c语言中使用链表的队列入队功能
问题描述
使用链表构建队列程序时遇到问题。这是完整的代码。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define ERROR_VALUE -300000
typedef struct LinkedNode {
int data;
struct LinkdedNode* link;
}Node;
Node* front;
Node* rear;
void init_queue() { front = rear = NULL; }
int is_empty() { return (front = NULL && rear == NULL); }
int size() {
Node* p;
int count = 0;
if (is_empty())
return 0;
for (p = front; p != rear; p = p->link) {
count++;
return count + 1;
}
}
void enqueue(int e) {
Node* p = (Node*)malloc(sizeof(Node));
p->data = e;
p->link = NULL;
if (is_empty())
front = rear = p;
else {
rear->link = p;
rear = p;
}
}
int dequeue() {
Node* p = front;
int e;
if (is_empty()) {
printf("Queue Empty Error!\n");
return ERROR_VALUE;
}
else if (size() == 1) {
front = rear = NULL;
}
else
front = p->link;
e = p->data;
free(p);
return e;
}
int peek() {
if (is_empty()) {
printf("Queue Empty Error!\n");
return ERROR_VALUE;
}
return front->data;
}
void print_queue() {
Node* p;
printf("QUEUE STATUS: size=%d\n", size());
if (is_empty())
return;
for (p = front; p != NULL; p = p->link)
printf("[%2d] ", p->data);
printf("\n");
}
int main(void) {
int val, sel;
init_queue();
while (1) {
do {
printf("1.ENQUEUE 2.DEQUEUE 3.PEEK 4.STATUS 0.EXIT :");
scanf("%d", &sel);
} while (sel < 0 || sel > 4);
if (sel == 1) {
printf("1.ENQUEUE VALUE ? ");
scanf("%d", &val);
enqueue(val);
}
else if (sel == 2) {
val = dequeue();
if (val != ERROR_VALUE)
printf("2.DEQUEUE VALUE = %d\n", val);
}
else if (sel == 3) {
val = peek();
if (val != ERROR_VALUE)
printf("3.PEEK VALUE = %d\n", val);
}
else if (sel == 4)
print_queue();
else if (sel == 0) break;
}
return 0;
}
我没有创建 is_full() 函数,因为链表是“动态的”。调试时,当我尝试将值排队时程序停止。我的猜测是入队函数有问题,但找不到什么。
解决方案
这是错误的:
int is_empty() { return (front = NULL && rear == NULL); }
注意front = NULL
. 这意味着每次调用时is_empty()
,front
都会设置为NULL
,然后is_empty()
返回0
,因为front = NULL
计算结果为NULL
。
您需要更改is_empty()
为
int is_empty() { return (front == NULL && rear == NULL); }
这正是为什么许多程序员使用“尤达条件”之类NULL == front
的原因——它们可以防止这种类型的错误,因为如果您编写=
而不是==
代码将无法编译。
而且,正如您所注意到的,在您自己的代码中很难发现此类错误。
推荐阅读
- node.js - 如何从下拉列表中选择任何值并在节点js的同一页面中的下一个下拉列表中自动获取另一个值
- python - Pydantic:检测字段值是否缺失或为空
- powershell - 带有 powershell 核心 7.1.2 或 7.2 的重音法语字符不起作用
- javascript - 这是 ES2015 标记模板的正确语法吗?
- database - 连接到远程 postgresql 服务器
- python - 使用 Docker 进行容器化时如何在 requirements.txt 中引用私有 bitbucket 包?
- c++ - 使用 const 指针作为参数调用非常量函数
- javascript - 遍历两个对象数组并比较具有相同 ID 的数据
- docker - 如何在不使用 swarm 的情况下连接 2 个 docker 主机
- python - 为矢量预测配置 SMOTE