JBTALKS.CC
标题:
C program Circular Queue
[打印本页]
作者:
狂天使
时间:
2010-12-26 11:56 PM
标题:
C program Circular Queue
各位大大幫忙一下,
我要寫一個 Circular Queue 我的問題是: 一開始 insert, 然後 insert 到 full 為之是沒問題,過後我delete 再 insert 就有問題了。
先謝謝各位。。
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct element
{
int key ;
};
struct MyCircularQueue{
struct element items[MAX] ;
int rear ;
int front ;
int count;
bool IsFullQ( ) ;
bool IsEmptyQ( ) ;
void AddQ( struct element ) ;
struct element DeleteQ( ) ;
void ShowQ( ) ;
} ;
bool MyCircularQueue::IsFullQ()
{
return rear-front==MAX;
}
bool MyCircularQueue::IsEmptyQ()
{
return front==rear;
}
void MyCircularQueue::AddQ(struct element elements)
{
rear=(rear+1) % MAX;
items[rear]=elements;
}
struct element MyCircularQueue::DeleteQ()
{
front=(front+1) % MAX;
return items[front];
}
void MyCircularQueue::ShowQ()
{
int flag=front;
for(;flag<rear;)
printf("Queue elements: %d\n",items[++flag]);
}
int main()
{
int choice,stop=0;
struct MyCircularQueue my_queue;
struct element elements;
my_queue.front=-1;
my_queue.rear=-1;
while(stop!=1)
{
printf("1)Check Queue is it Full\n");
printf("2)Check Queue is it Empty\n");
printf("3)Insert element into Queue\n");
printf("4)Delete element from Queue\n");
printf("5)Print out all element of Queue\n");
printf("6)Exit\n");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(my_queue.IsFullQ())
printf("\nQueue is full\n\n");
else
printf("\nQueue not full still can input %d elements\n\n",MAX-1-my_queue.rear);
break;
case 2:
if(my_queue.IsEmptyQ())
printf("\nQueue is Empty\n\n");
else
printf("\nGot %d elements in Queue\n\n",my_queue.rear-my_queue.front);
break;
case 3:
if(!my_queue.IsFullQ()){
printf("\nInsert the elements:");
scanf("%d",&(elements.key));
my_queue.AddQ(elements);
}else
printf("\ncannot add any more...\n\n");
break;
case 4:
if(!my_queue.IsEmptyQ()){
my_queue.DeleteQ();
}else
printf("\nqueue already empty\n\n");
break;
case 5:
my_queue.ShowQ();
break;
case 6:
stop++;
system("cls");
break;
}
}
}
复制代码
作者:
Super-Tomato
时间:
2010-12-27 12:30 AM
因為你的 Array 没有在 delete 的時候重新排好記憶體分配的位置,你可以在 delete 之後执行 showQ 並列出你的 flag 看看就會明白
欢迎光临 JBTALKS.CC (https://www.jbtalks.cc/)
Powered by Discuz! X2.5