首页 > 解决方案 > 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() 函数,因为链表是“动态的”。调试时,当我尝试将值排队时程序停止。我的猜测是入队函数有问题,但找不到什么。

标签: cdata-structures

解决方案


这是错误的:

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的原因——它们可以防止这种类型的错误,因为如果您编写=而不是==代码将无法编译。

而且,正如您所注意到的,在您自己的代码中很难发现此类错误。


推荐阅读