/*请设计一个队列,要求满足:1.初始时队列为空;2.入队时,允许增加队列占用空间;3.出队后,出队元素所占用的
空间可重复使用,即整个队列所占用的空间值增不减;4.入队操作和出队操作的时间复杂度始终保持为O(1)*/
//想法:与顺序循环存储队列相似
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode;
typedef struct{
LNode *front,*rear;
}Queue;
void InitQueue(Queue &Q)
{
Q.front = Q.rear = (LNode*)malloc(sizeof(LNode));
Q.rear->next = Q.front;
}
bool IsEmpty(Queue Q)
{
if(Q.front == Q.rear)
return true;
else
return false;
}
bool IsOverflow(Queue Q)
{
if(Q.rear->next == Q.front)
return true;
else
return false;
}
bool EnQueue(Queue &Q,ElemType x)
{
if(IsOverflow(Q))
{
LNode *s = (LNode*)malloc(sizeof(LNode));
Q.rear->data = x;
s->next = Q.rear->next;
Q.rear->next = s;
Q.rear = s;
}else{
Q.rear->data = x;
Q.rear = Q.rear->next;
}
return true;
}
bool DeQueue(Queue &Q,ElemType &x)
{
if(IsEmpty(Q))
return false;
x = Q.front->data;
Q.front = Q.front->next;
return true;
}
void main()
{
Queue Q;
ElemType getVal;
InitQueue(Q);
EnQueue(Q,1);
EnQueue(Q,2);
EnQueue(Q,3);
DeQueue(Q,getVal);
DeQueue(Q,getVal);
printf("%d\n",getVal);
}
如有问题,欢迎随时指出,与讨论~