c - 这段C代码的bug在哪里?

标签 c data-structures queue

我对编程很陌生。我想写一个程序来实现带有数组的队列(循环队列)。我认为从队列函数中插入和删除元素是正确的,但显示函数存在一些问题。当队列已满时,如果我尝试插入更多元素,它不会根据函数显示“队列已满”,而是会在元素旁边显示一些垃圾值。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>  
#include <ctype.h>
#include <string.h>

#define m 3   // maximum size of array
int Q[m];
int f=-1,r=-1,s;        //f=front,r=rear,s=rear in another term for finding wheather is 

queue full


int enQueue(int item){
    s = (r+1)%(m+1);
    if(f == s)
        printf("\nQUEUE FULL"); 
    else{
        Q[s] = item;
        r = s;
    }

return 0;
}


int deQueue(){
    int item;
    if(f == r)
        printf("\nQUEUE UNDERFLOW");
    else{   
        f = (f+1)%(m+1);
        item = Q[f];
        Q[f] = NULL;
    }

return 0;
}

void displayQueue(){
    int i;
    if(f == r) 
        printf(" \n The queue is empty\n");
    else {
        printf("\nQUEUE IS : \n");
        for(i=f+1; i<=s; i++) {
            printf("%d\t", Q[i]);
        }
        printf("\n\n********************************************");
    }

}



int main(){
    int item,i,j;

    while (1){
        printf("\n\nENTER ITEM TO INSERT : ");
        scanf("%d", &item);

        enQueue(item);
        displayQueue();
    }

 _getch();
 return 0;
}

最佳答案

代码有很多问题。本回复仅涉及问题范围内的内容。希望对您有所帮助。

int enQueue(int item){
   if(r+1 >= m)   //check against queue size first...
        printf("\nQUEUE FULL"); 
   else{
        s = (r+1)%(m);
        Q[s] = item;
        r = s;
    }
return 0;        //the return value part could be written better...
}

关于c - 这段C代码的bug在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36963521/

相关文章:

algorithm - 实现单词词典的数据结构

data-structures - 一个模块中的 Rc<T>s 和另一个模块中的 Rc<RefCell<T>>s 引用相同的数据

c++ - 如何将 std::queue<char> 复制到 std::string?

c - 共享库中的 gdb 断点不起作用

无法将新创建的链表分配给另一个变量

algorithm - 无向图中直径和半径的关系?

python - 使用python实现队列

javascript - 在同一时刻多次调用函数,但在nodejs中延迟执行不同的调用

c++ - "fast"或 "normal"在 "free(): invalid next size (fast)"中是什么意思?

类型转换指针警告