我第一次实现的时候竟然是用链表实现的。。。哎,这种zz的事,就莫再提了,转载文章:https://blog.csdn.net/Vit_rose/article/details/52781124
其实和前面顺序栈差不多,但是就是在判断指针的下一个位置的时候
q->rear = (q->rear+1)%MAXQSIZE;
q->front = (q->front+1)%MAXQSIZE;
判断队列的长度的时候:
return (q.rear-q.front+MAXQSIZE)%MAXQSIZE;
//顺序实现队列
//若长度无法估计宜使用链队列
//用链表来实现
//使用方法二,当队头指针在队尾指针下一个位置时才判断队列为满
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define FALSE 0
#define TRUE 1
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXQSIZE 100
typedef int QElemType;
typedef int Status;
typedef struct
{
QElemType *base;
int front;
int rear;
}Squeue;
Status
InitQueue(Squeue *q)
{
q->base = (QElemType*)malloc(MAXQSIZE*sizeof(QElemType));
if(!q->base)
exit(OVERFLOW);
q->front = q->rear = 0;
return OK;
}
int
QueueLength(Squeue q)
{
return (q.rear-q.front+MAXQSIZE)%MAXQSIZE;
}
Status
EnQueue(Squeue *q,QElemType e)
{
if( (q->rear+1) %MAXQSIZE == q->front )
return ERROR;
q->base[q->rear] = e;
q->rear = (q->rear+1)%MAXQSIZE;
return OK;
}
Status
DeQueue(Squeue *q,QElemType *e)
{
if(q->front == q->rear)
return ERROR;
*e = q->base[q->front];
q->front = (q->front+1)%MAXQSIZE;
return OK;
}
Status TraverseQueue(Squeue q)
{
if(q.front == q.rear){
printf("队列为空\n");
return ERROR;
}
int i = q.front;
while(i%MAXQSIZE != q.rear)
printf("%d ",q.base[i++]);
printf("\n");
return OK;
}
int main()
{
Squeue q;
QElemType e;
printf("初始化一个空队列:\n");
InitQueue(&q);
TraverseQueue(q);
printf("\n构造队列 1...10 :\n");
int i;
for(i = 1;i<=10;++i)
EnQueue(&q,i);
TraverseQueue(q);
printf("\n在队列尾插入元素 13 :\n");
EnQueue(&q,13);
TraverseQueue(q);
printf("\n删除队头元素,用e返回该删除值:\n");
DeQueue(&q,&e);
TraverseQueue(q);
printf("被删除的元素 e = %d\n",e);
return 0;
}