队列:顺序实现
项目结构:
main.cpp:
#include <iostream> #include<stdio.h> #include<stdlib.h> #include "function_for_SqQueue.h" using namespace std; int main() { TestSqQueue(); return 0; }
function_for_SqQueue.h:
#ifndef FUNCTION_FOR_SQQUEUE_H_INCLUDED #define FUNCTION_FOR_SQQUEUE_H_INCLUDED #define MAXSIZE 100 typedef char ElemType; typedef struct{ ElemType *base; //初始化的动态分配存储空间 int head; //对头元素下标 int rear; //队尾元素的下一个位置 }SqQueue; /* 循环队列 ----解决 ‘ 假上溢 ’ */ //初始化 void InitQueue(SqQueue &Q); //求队列长度 int QueueLength(SqQueue Q); //(队尾)入队 void InsertQueue(SqQueue &Q, ElemType e); //(队头)出队 ElemType DelHeadQueue(SqQueue &Q); //取队头元素 ElemType GetHead(SqQueue &Q); //打印队列元素(从头到尾) void PrintQueue(SqQueue &Q); //测试 void TestSqQueue(); #endif // FUNCTION_FOR_SQQUEUE_H_INCLUDED
function_for_SqQueue.cpp:
#include<stdio.h> #include<stdlib.h> #include "function_for_SqQueue.h" /* 循环队列 ----解决 ‘ 假上溢 ’ */ //初始化 void InitQueue(SqQueue &Q){ Q.base = (ElemType *)malloc(sizeof(SqQueue) * MAXSIZE); if(!Q.base) exit(0); //若存储分配失败,则退出 Q.head=0; //首尾下标置为0,表示队列为空 Q.rear=0; } //求队列长度 int QueueLength(SqQueue Q){ return ((Q.rear-Q.head+MAXSIZE)%MAXSIZE); //核心算法 } //(队尾)入队 void InsertQueue(SqQueue &Q, ElemType e){ if((Q.rear+1)%MAXSIZE == Q.head) exit(0); //队列已满,不可插入 Q.base[Q.rear] = e; Q.rear = (Q.rear+1)%MAXSIZE; //队尾下标加1 } //(队头)出队 ElemType DelHeadQueue(SqQueue &Q){ if(Q.head == Q.rear) exit(0); //队空 ElemType e = Q.base[Q.head]; Q.head = (Q.head+1)%MAXSIZE; //队头指针加1 return e; //返回队头元素数据域 } //取队头元素 ElemType GetHead(SqQueue &Q){ if(Q.head != Q.rear){ //队列不为空 return Q.base[Q.head]; //获取队头元素的值,队列本身不变 } } //打印队列元素(从头到尾) void PrintQueue(SqQueue &Q){ int p=Q.head; //设置游标,开始时指向队头位置 while(p != Q.rear){ printf("%c ", Q.base[p]); p = (p+1)%MAXSIZE; } } //测试 void TestSqQueue(){ SqQueue Q; printf(" 初始化: "); InitQueue(Q); printf(" 依次插入元素(a,b,c,d,e): "); InsertQueue(Q, 'a'); InsertQueue(Q, 'b'); InsertQueue(Q, 'c'); InsertQueue(Q, 'd'); InsertQueue(Q, 'e'); printf(" 打印队列(从头到尾): "); PrintQueue(Q); printf(" 再插入一个元素: "); InsertQueue(Q, 'f'); printf(" 打印队列(从头到尾): "); PrintQueue(Q); printf(" 出队列: "); printf("出队列后获得队头元素:%c ", DelHeadQueue(Q)); printf(" 打印队列(从头到尾): "); PrintQueue(Q); printf(" 此时获取队头元素:%c ", GetHead(Q)); printf(" 打印队列(从头到尾): "); PrintQueue(Q); }
运行结果: