头文件SeqQueue.h
#include<stdio.h> #include<malloc.h> #include<assert.h> #define MAXSIZE 10 typedef int ElemType; typedef struct Queue { ElemType *base; int front; int rear; }Queue; void InitQueue(Queue*Q); void EnQueue(Queue *Q, ElemType x); void Show(Queue*Q); void DeQueue(Queue *Q); ElemType Length(Queue *Q); void GetHead(Queue *Q, ElemType *x); void Clear(Queue *Q); void Destroy(Queue *Q);
函数实现SeqQueue.c
#include"SeqQueue.h" void InitQueue(Queue*Q) { Q->base = (ElemType *)malloc(sizeof(ElemType)* MAXSIZE); assert(Q->base != NULL); Q->front = Q->rear = 0; } void EnQueue(Queue *Q, ElemType x) { if (Q->rear >= MAXSIZE)//队列空间已经满 return; else Q->base[Q->rear++] = x; } void Show(Queue*Q) { for (int i = Q->front; i < Q->rear; i++) printf("%d ", Q->base[i]); printf("\n"); } void DeQueue(Queue *Q) { if (Q->front == Q->rear)//队列已空 return; Q->front++; } void GetHead(Queue *Q, ElemType *x) { if (Q->front == Q->rear)//队列已空 return; *x = Q->base[Q->front]; } ElemType Length(Queue *Q) { return (Q->rear - Q->front); } void Clear(Queue *Q) { Q->front = Q->rear = 0; } void Destroy(Queue *Q) { free(Q->base); Q->base = NULL; }
测试函数Main.c
#include"SeqQueue.h" int main() { Queue Q; InitQueue(&Q); for (int i = 1; i <= 5; i++) { EnQueue(&Q, i); } Show(&Q); DeQueue(&Q); Show(&Q); }