//SeqQueue.h
#ifndef _SEQQUEUE_H_
#define _SEQQUEUE_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10
#define INCREASE 6
typedef int ElementType;
typedef struct SeqQueue
{
ElementType *base;
int head; //队头指针
int tail; //队列尾后指针
int capacity;
}SeqQueue;
bool InitSeqQueue(SeqQueue *sq);
bool increase(SeqQueue *st);
bool EnSeqQueue(SeqQueue *sq, ElementType e);
void ShowSeqQueue(SeqQueue sq);
bool DeSeqQueue(SeqQueue *sq);
int length(SeqQueue sq);
bool IsFull(SeqQueue sq);
bool IsEmpty(SeqQueue sq);
bool GetTop(SeqQueue sq, ElementType *e);
void Clear(SeqQueue *sq);
void Destroy(SeqQueue *sq);
#endif //_SEQQUEUE_H_
#include "SeqQueue.h"
bool InitSeqQueue(SeqQueue *sq)
{
ElementType *p = (ElementType *)malloc(MAXSIZE * sizeof(ElementType));
if( NULL == p )
return false;
sq->base = p;
sq->head = sq->tail = 0;
sq->capacity = MAXSIZE;
return true;
}
bool increase(SeqQueue *sq)
{
ElementType *newBase = (ElementType *)realloc(sq->base, sizeof(ElementType) * (MAXSIZE + INCREASE));
if (NULL == newBase)
return false;
sq->base = newBase;
//两指针不变
sq->capacity += INCREASE;
return true;
}
bool EnSeqQueue(SeqQueue *sq, ElementType e)
{
if( IsFull(*sq) && !increase(sq) )
{
printf("队列已满\n");
return false;
}
sq->base[sq->tail++] = e;
return true;
}
void ShowSeqQueue(SeqQueue sq)
{
for (int i = sq.head; i != sq.tail; i++)
{
printf("%d\n", sq.base[i]);
}
}
bool DeSeqQueue(SeqQueue *sq)
{
if( IsEmpty(*sq) )
{
printf("队列为空\n");
return false;
}
sq->head++;
return true;
}
int length(SeqQueue sq)
{
return sq.tail - sq.head;
}
bool IsFull(SeqQueue sq)
{
return sq.capacity <= sq.tail;
}
bool IsEmpty(SeqQueue sq)
{
return sq.head == sq.tail;
}
bool GetTop(SeqQueue sq, ElementType *e)
{
if( IsEmpty(sq) )
{
printf("队列为空\n");
return false;
}
*e = sq.base[sq.head];
return true;
}
void Clear(SeqQueue *sq)
{
sq->head = sq->tail = 0;
}
void Destroy(SeqQueue *sq)
{
free(sq->base);
sq->base = NULL;
sq->head = sq->tail = 0;
sq->capacity = 0;
}
//main.c
#include "SeqQueue.h"
void main()
{
SeqQueue sq;
ElementType e;
InitSeqQueue(&sq);
for(int i = 0; i != 15; i++)
EnSeqQueue(&sq, i);
printf("显示\n");
ShowSeqQueue(sq);
if( GetTop(sq, &e) )
printf("队头元素为%d\n", e);
printf("出队\n");
for (int i = 0; i != 5; i++)
DeSeqQueue(&sq);
printf("显示\n");
ShowSeqQueue(sq);
printf("队列长度为%d\n", length(sq));
if (GetTop(sq, &e))
printf("队头元素为%d\n", e);
printf("清除\n");
Clear(&sq);
printf("显示\n");
ShowSeqQueue(sq);
Destroy(&sq);
system("pause");
}
本文介绍了一种基于数组实现的队列数据结构,并提供了初始化、入队、出队等核心操作的具体实现。通过动态扩容解决了固定大小数组带来的限制,展示了队列的基本使用案例。
292

被折叠的 条评论
为什么被折叠?



