順序佇列的基本操作-C語言
阿新 • • 發佈:2018-12-30
順序佇列的基本操作
順序佇列即用順序表實現的佇列, 其操作簡便, 但是會出現"假溢位"的現象, 這是由於順序表的定義以及佇列的特點所共同決定的
具體實現
順序佇列的定義
//定義一個順序佇列
#define QUEUESIZE 100
typedef struct Squeue {
int queue[QUEUESIZE];
int front;
int rear;
}SeQueue;
順序佇列的初始化
//順序佇列的初始化
void InitQueue(SeQueue* S) {
S->front = S->rear = 0;
}
判斷佇列是否為空
//判斷佇列是否為空
int IsEmpty(SeQueue S) {
if (S.front == S.rear) {
return 1;
}
return 0;
}
入隊操作
//入隊操作
int InQueue(SeQueue* S, int e) {
//判斷佇列是否為滿
if (S->rear >= QUEUESIZE) {
return 0;
}
S->queue[S->rear] = e;
++S->rear;
return 1;
}
出隊操作
//出隊操作
int OutQueue(SeQueue* S, int * e) {
//判斷佇列是否為空
if (IsEmpty(*S)) {
return 0;
}
*e = S->queue[S->front];
++S->front;
return 1;
}
測試
#include <stdio.h>
#include <windows.h>
//定義一個順序佇列
#define QUEUESIZE 100
typedef struct Squeue {
int queue[QUEUESIZE];
int front;
int rear;
}SeQueue;
//順序佇列的初始化
void InitQueue (SeQueue* S) {
S->front = S->rear = 0;
}
//判斷佇列是否為空
int IsEmpty(SeQueue S) {
if (S.front == S.rear) {
return 1;
}
return 0;
}
//入隊操作
int InQueue(SeQueue* S, int e) {
//判斷佇列是否為滿
if (S->rear >= QUEUESIZE) {
return 0;
}
S->queue[S->rear] = e;
++S->rear;
return 1;
}
//出隊操作
int OutQueue(SeQueue* S, int* e) {
//判斷佇列是否為空
if (IsEmpty(*S)) {
return 0;
}
*e = S->queue[S->front];
++S->front;
return 1;
}
int main() {
SeQueue s1;
InitQueue(&s1);
for (int i = 0; i < 5; ++i) {
if (InQueue(&s1, i + 1));
}
int e = 0;
for (int i = 0; i < 5; ++i) {
if (OutQueue(&s1, &e)) {
printf("%d ", e);
}
}
printf("\n");
system("pause");
return 0;
}
效果圖
希望該文章能對大家有所幫助
同時真誠接受各位寶貴的評論和建議