2016-05-01 42 views
-3

我在編程方面很新穎。我想寫一個程序來實現帶有數組的隊列(循環隊列)。我認爲從隊列函數中插入&刪除元素是正確的,但在顯示函數中存在一些問題。當隊列滿時,如果我嘗試插入更多元素,它不會按照函數顯示「QUEUE FULL」,它會在元素旁邊顯示一些垃圾值。這個C代碼中的錯誤在哪裏?

#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; 
} 
+3

您是否使用調試器? – MikeCAT

+3

爲什麼用'm + 1'來代替'm'來分割數字?有訪問數組超出範圍的風險! – MikeCAT

+0

我在Visual Studio 12中編寫了這段代碼@ MikeCAT – Fsalad

回答

1

的代碼有相當多的問題。這個回覆僅涉及問題範圍內的內容。希望它可以幫助。

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... 
} 
+0

現在它工作正常 – Fsalad

1

的問題是在enQueue()功能if條件。

f是-1在整個程序中沒有得到改變,並且s將永遠不會是-1,因此條件永遠不會生效。

將if條件從s == f更改爲s==m,即。

if(s == m) 
    printf("Queue is full"); 

再次運行程序。 我已經測試過它。

1

,你可以嘗試一種新的計數變量,這樣就可以跟蹤數組中元素的個數呈現時間

initialize the count to 0 as global 
if enque 
check count for the overflow 
if not 
    add element and increase the count 
if deque 
check count for the underflow 
if not 
    delete the element and decrese the count