C language – the basic operation of the queue
content
Create a sequential queue to implement data entry and exit operations, and then verify the first-in-first-out characteristics of the queue. Proceed as follows:
- Create enqueue and dequeue functions;
- Enter data in the main function, end with '\0', and call the enqueue and dequeue functions.
- And the basic operation of the queue.
experimental code
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAX 100
typedef int QElemType;
typedef struct
{
QElemType *base;
int front;
int rear;
}SqQueue;
void InitQueue(SqQueue &Q);//队列的初始化函数
void SetQueue(SqQueue &Q);//建立一个顺序队列函数
int QueueLength(SqQueue Q);//查看队列长度函数
void EnQueue(SqQueue &Q,QElemType e);//入队函数
void DeQueue(SqQueue &Q,QElemType &e);//出队函数
QElemType GetHead(SqQueue Q);//取队头元素操作函数
void OutQueue(SqQueue &Q);//遍历队列元素函数
void InitQueue(SqQueue &Q)
{
Q.base=(QElemType*)malloc(sizeof(QElemType)*MAX);
if(!Q.base)
printf("存储队列失败\n");
Q.front=Q.rear=0;
printf("顺序队列成功初始化\n");
}
void EnQueue(SqQueue &Q,QElemType e)
{
if(QueueLength(Q)>=MAX-1)
printf("队列已满\n");
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAX;
printf(" %d ",e);
}
void SetQueue(SqQueue &Q)
{
QElemType e;
printf("请依次输入队列元素,并输入0作为结束标括志:");
while(1)
{
scanf("%d",&e);
if(e==0)
break;
EnQueue(Q,e);
}fflush(stdin);
}
int QueueLength(SqQueue Q)
{
return (abs(Q.rear-Q.front)+MAX)%MAX;
}
void DeQueue(SqQueue &Q,QElemType &e)
{
if(Q.rear==Q.front)
printf("队列为空\n");
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAX;
}
QElemType GetHead(SqQueue Q)
{
if(Q.rear==Q.front)
printf("队列为空!\n");
return Q.base[Q.front];
}
void OutQueue(SqQueue &Q)
{
QElemType s;
s=Q.front;
if(Q.front==Q.rear)
printf("队列为空\n");
else
{
printf("顺序队列依次为a:");
while(s<Q.rear)
{
printf(" %d ",Q.base[s]);
s=s+1;
}
printf("\n");
}
}
int main()
{
QElemType x;
SqQueue T;
int k,y;
do
{
printf("\n");
printf("1、队列的初始化\n");
printf("2、建立顺序队列\n");
printf("3、查看队列长度操作\n");
printf("4、入队操作\n");
printf("5、出队操作\n");
printf("6、取队头操作\n");
printf("0、结束程序运行!\n");
printf("请输入你要选择操作:0,1,2,3,4,5,6");
printf("\n\n\n");
printf("===========================\n");
scanf("%d",&k);
switch(k)
{
case 1:
InitQueue(T);
break;
case 2:
SetQueue(T);
printf("\n已建立顺序队列\n");
OutQueue(T);
break;
case 3:
printf("队列长度为:%d\n",QueueLength(T));
OutQueue(T);
break;
case 4:
printf("请输入入队的值:");
scanf("%d",&x);
EnQueue(T,x);
printf("\n");
OutQueue(T);
break;
case 5:
DeQueue(T,x);
printf("出队元素的值: %d\n",x);
OutQueue(T);
break;
case 6:
y=GetHead(T);
printf("队头元素:%d",y);
break;
case 0:
return 0;
}
}while(k!=0);
}
result
1. Initialize the queue
2. Establish a sequential queue
3. Check the queue length
4. Enqueue operation
5. Dequeue operation
6. Take queue head operation and end program operation
come on! Come on! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !