繁体   English   中英

使用 c 中的链表将队列的 function 入队

[英]Enqueue function of queue using linked list in 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() function 因为链表是“动态的”。 调试时,当我尝试将值排队时程序停止。 我的猜测是排队 function 有问题,但找不到什么。

这是错误的:

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这样的“Yoda 条件”的原因 - 他们防止了这种类型的错误,因为如果你写=而不是==代码将无法编译。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM