定义队列的基本结构
/*0.定义队列的基本结构*/
typedef struct {
ElemType data[Maxsize]; //用静态数组存放队列元素
int front, rear; //队头指针与队尾指针
}SqQueue;
初始化
/*1.初始化队列*/
void InitQueue(SqQueue& Q)
{//初试时,队头、队尾指针指向0
Q.front = Q.rear = 0;
}
判空
/*2.判断队列空*/
Status QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
else
return false;
}
入队
/*3.入队*/
Status EnQueue(SqQueue& Q, ElemType x)
{
if (Q.rear == Maxsize) //会存在假上溢
return false;//队满则报错
Q.data[Q.rear] = x; //将x插入队尾
Q.rear++;
return true;
}
出队
/*4.出队*/
Status DeQueue(SqQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false; //队空则报错
x = Q.data[Q.front]; //将队头元素赋给x
Q.front++;
return true;
}
顺序队列的完整代码
/*实现静态队列的基本操作*/
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 20
typedef int ElemType;
typedef bool Status;
/*0.定义队列的基本结构*/
typedef struct {
ElemType data[Maxsize]; //用静态数组存放队列元素
int front, rear; //队头指针与队尾指针
}SqQueue;
/*1.初始化队列*/
void InitQueue(SqQueue& Q)
{//初试时,队头、队尾指针指向0
Q.front = Q.rear = 0;
}
/*2.判断队列空*/
Status QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
else
false;
}
/*3.入队*/
Status EnQueue(SqQueue& Q, ElemType x)
{
if (Q.rear == Maxsize) //会存在假上溢
return false;//队满则报错
Q.data[Q.rear] = x; //将x插入队尾
Q.rear++;
return true;
}
/*4.出队*/
Status DeQueue(SqQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false; //队空则报错
x = Q.data[Q.front]; //将队头元素赋给x
Q.front++;
return true;
}
int main()
{
SqQueue Q;
ElemType x;
InitQueue(Q);
EnQueue(Q, 3);
EnQueue(Q, 6);
EnQueue(Q, 8);
EnQueue(Q, 9);
DeQueue(Q, x);
printf("%d\n", x);
return 0;
}