循环队列
这道题的叙述有点问题,我也是看到网上的大佬才发现其实是题目描述的输入输出存在问题
题上说队满时输出yes;但是到了下边给的例子:
yes就变成了输入,导致当初WA了很多次。
一、题目解析
本题要求使用循环队列,队列(queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。
队列常见的存储结构分为顺序存储结构和链式存储结构,笔者采用链式存储结构。
二、代码分析
#include <stdio.h>
#include <stdlib.h>
//创建node结构体用于存储队列元素
typedef struct node
{
int data;
struct node*next;
}Node,*ListNode;
//队列
typedef struct queue
{
ListNode front;
ListNode rear;
}LinkQueue;
//初始化队列
void InitQueue (LinkQueue *s)
{
s->front=s->rear=(ListNode)malloc(sizeof(Node));//初始化,队首队尾指向同一结点
s->front->next=NULL;
}
//添加元素
void AddQueue (LinkQueue *s,int a)
{
ListNode q=(ListNode)malloc(sizeof(Node));
q->data=a;
q->next=s->front;//与队首连接
s->rear->next=q;//队尾插入
s->rear=q;
}
//出队返回队首元素
int DeQueue (LinkQueue *s)
{
ListNode p;
int temp;
if(s->front == s->rear) printf("队列已空");
else
{
p=s->front->next->next;
s->front->next=p;//删除第一个元素
temp=p->data;//返回第二个,即删除后的队首元素
}
return temp;
}
//判满,结果这道题yes为输入,可以不用了
int JudgeFull(LinkQueue *s,int n)
{
int i=0;
ListNode p=s->front->next;
while(p!=s->front)
{
i++;
p=p->next;
}
if(i==n) return 1;
else return 0;
}
int main()
{
int n;
scanf("%d",&n);
LinkQueue Q;
InitQueue (&Q);
while(1)
{
int a;
scanf("%d",&a);
AddQueue(&Q,a);
char c=getchar();//接受非数字字符
if(c==' ') continue;
if(c=='\n') break;
}
// int f=JudgeFull(&Q,n);原本用来判满,现在为了ce用不上了
// if(f==0) printf("no");
// else printf("yes");
char s[5];//随便一个字符串输入yes
scanf("%s",s);
int d,head;//d为要删除的元素 head接收出对的返回元素
scanf("%d",&d);
while(Q.front->next->data!=d)//把的之前的全部出列
{
head=DeQueue(&Q);
}
head=DeQueue(&Q);//出列d
ListNode qq=Q.front->next;//遍历输出剩下的队列元素
while(qq!=Q.front)
{
printf("%d ",qq->data);
qq=qq->next;
}
printf("\n");
printf("%d ",head);
return 0;
}
🆗啦就这样吧。