使用链表构建队列程序时遇到问题。这是完整的代码。
#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=%dn", 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 = %dn", val);
}
else if (sel == 3) {
val = peek();
if (val != ERROR_VALUE)
printf("3.PEEK VALUE = %dn", 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); }
这正是许多程序员使用";Yoda条件";像NULL == front
一样,它们可以防止这种类型的错误,因为如果您编写=
而不是==
,代码将无法编译。
而且,正如您所注意到的,在您自己的代码中很难发现这样的错误。