在前面的两篇关于队列的文章后,今天这篇文章我们来讲讲它的应用。刚好前几天我们在上数据结构课上,老师给我们留下了一道作业题。
题目:问题描述
设有个人站成一排,从左向右的躺号分别为1~ n ,现在从左往右报数“1,2,1,
2,…”,数到“1”的人出列,数到“2”的立即站到队伍的量右鸡。报数过程反复进行,直划个人都出为止。要求给出他们的出列心序。
例如,当 n =8时,初始序列为
12345678
则出列順序为
13572648
为了帮同学更加了解题意,老师还随机叫了8名同学到讲台上排成一列,每人手里有编号。执行题意的操作.上天就是这么眷念博主我,我就是被叫上去的8人之一(已经不是第一次了)。
其实,分析这道题:这就是一个出队,打印,再出队到入队。这是这两步一直循环。
解题代码:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node* next;
};
typedef struct
{
Node *front;
Node *rear;
}SqQueue;
bool InitQueue(SqQueue* Q)
{
Q->front = (Node*)malloc(sizeof(Node));///给头尾指针分配内存,让队列中的头尾指针指向 同一个内存
Q->rear = Q->front;
if (!Q->front)
{
return false;
}
Q->front->next = NULL;
return true;
}
int enQueue(SqQueue* Q, int i)
{
Node *p;
p = (Node*)malloc(sizeof(Node));
if (!p)
{
exit(0);
}
p->data = i;//先赋值
p->next = NULL;
Q->rear->next = p;//再后移
Q->rear = p;
return true;
}
int deQueue(SqQueue* Q, ElemType* e)
{
struct Node *p;
if (Q->front == Q->rear)
return false;
p = Q->front->next;
*e = p->data;//先赋值
Q->front->next = p->next;//再后移
if (Q->rear == p)//到达队列末尾
Q->rear = Q->front;
free(p);
return true;
}
int DestroyQueue(SqQueue* Q)
{
while (Q->front)
{
Q->rear = Q->front->next;///队尾指针始终指向队头指针的下一个元素
free(Q->front);
Q->front = Q->rear;///调整队头指针
}
return true;
}
int QueueEmpty(SqQueue* Q)
{
if (Q->front->next == NULL)
return true;
else return false;
}
void number(int n)
{
int i; ElemType e;
SqQueue* Q = (SqQueue*)malloc(sizeof(SqQueue));
InitQueue(Q);
for (i = 1; i <= n; i++)
{
enQueue(Q, i);
}
printf("报数出列顺序;");
while (!QueueEmpty(Q))
{
deQueue(Q, &e);//出去一个
printf("\n");
printf("%d\n", e);//打印那一个
if (!QueueEmpty(Q))
{
deQueue(Q, &e);//再出去一个
printf("出去的元素为:%d",e);
enQueue(Q, e);//刚刚那个出去的再进去
}
}
printf("\n");
DestroyQueue(Q);
}
int main()
{
int n;
scanf_s("%d", &n);
number(n);
return 0;
}
执行结果:
好啦,今天的分享就到这吧。
本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览.
1005

被折叠的 条评论
为什么被折叠?



