求助。关于数据结构——队列的编程问题~

lianglevel 2012-05-06 09:28:52
其他测试正常,就是当队列只有一个元素的时候出队有问题。请教~

#include<stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
/*顺序队列的类型定义*/
typedef struct
{
int data[MAXSIZE];
int front,rear;
}sequeue;
/*初始化队列操作*/
void iniqueue(sequeue * q)
{
q->front=0;
q->rear=0;
}
/*入队列操作*/
int addqueue(sequeue * q,int x)
{
if((q->rear+1)%MAXSIZE==q->front)
return 0; //队列已满无法插入元素返回0
else
{
q->rear=(q->rear+1)%MAXSIZE;
q->data[q->rear]=x;
return 1; //返回插入成功标志1
}
}
/*出队列操作*/
int outqueue(sequeue * q,int &x)
{
if (q->rear==q->front)
return 0; //队列已空无法删除元素返回0
else
{
q->front=(q->front+1)%MAXSIZE;
x=q->data[q->front];
return 1; //返回删除成功标志1
}
}
/*读队头元素操作*/
int gethead(sequeue * q,int &x)
{
if(q->rear==q->front)
return 0; //队列已空无法读取队头元素
else
{
x=q->data[(q->front+1)%MAXSIZE];
return 1;
}
}
/*判断队列空操作*/
int empty(sequeue * q)
{
if(q->rear==q->front)
return 1; //队空标志1
else
return 0;
}
/*显示顺序队列的所有元素*/
void display(sequeue * q)
{
int i;
printf("输出队列的所有元素:");
for(i=q->front+1;i!=q->rear;i++)
printf("%d->",q->data[i]);
printf("%d\n",q->data[i]);
printf("\n");
}
/*菜单栏*/
void menu()
{
printf("\n***************************\n");
printf("[1]新建队列 \n");
printf("[2]入队列 \n");
printf("[3]出队列 \n");
printf("[4]遍历整个队列 \n");
printf("[0]退出 \n");
printf("\n***************************\n");
printf("请输入命令:\n");
}
/*主函数*/
void main()
{
sequeue * Q=(sequeue *)malloc(sizeof(sequeue));
int x; //队列元素
int flag; //标志
int order; //命令
char ans; //(Y/N)
//char temp;
iniqueue(Q);
while(1)
{
menu();
ans='n';
scanf("%d",&order);
switch(order)
{
case 1: //新建队列
do
{
printf("请输入队列的元素:\n");
scanf("%d",&x);
fflush(stdin); //清空键盘缓冲区(过滤回车)
addqueue(Q,x);
printf("是否继续添加元素?(Y/N)");
scanf("%c",&ans);
fflush(stdin); //清空键盘缓冲区(过滤回车)
}while(ans=='y' || ans =='Y');
display(Q);
break;
case 2: //入队列
if(empty(Q))
{
printf("队列为空!\n");
break;
}
do
{
printf("请输入添加到队列的元素:\n");
scanf("%d",&x);
fflush(stdin); //清空键盘缓冲区(过滤回车)
addqueue(Q,x);
printf("是否继续添加元素?(Y/N)");
scanf("%c",&ans);
fflush(stdin); //清空键盘缓冲区(过滤回车)
}while(ans=='y' || ans =='Y');
display(Q);
break;
case 3: //出队列
if(empty(Q))
{
printf("队列为空!\n");
break;
}
else
{
do
{
outqueue(Q,x);
fflush(stdin); //清空键盘缓冲区(过滤回车)
printf("元素%d已经出队列\n",x);
if(empty(Q)==0)
{
printf("是否继续出队列?(Y/N)");
scanf("%c",&ans);
}
else
{
printf("队列已空!\n");
break;
}
}while(ans=='y' || ans =='Y');
display(Q);
break;
}
case 4: //遍历整个队列
if(empty(Q))
{
printf("队列为空!\n");
break;
}
display(Q);
break;
case 0:
exit(0);
default:
printf("您输入的命令有误!\n");
}
}
}
...全文
90 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
猪头小哥 2012-05-06
  • 打赏
  • 举报
回复
在这个函数里面加个判断队列是否为空。
void display(sequeue * q)
{
if (empty(q))
{
printf("队列为空,显示失败!");
exit(-1);
}
int i;
printf("输出队列的所有元素:");
for(i=q->front+1;i!=q->rear;i++)
printf("%d->",q->data[i]);
printf("%d\n",q->data[i]);
printf("\n");
}

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧