链表实现
#include <cstdio>
#define null NULL
using namespace std;
struct node
{
node* nxt;
int val;
};
struct queue
{
node* front;
node* rear;
queue()
{
front=rear=null;
}
void push(int val)
{
node* x = new node();
x->val=val;
x->nxt=null;
if(rear==null)
{
front=x;
rear=x;
}
else
{
rear->nxt=x;
rear=x;
}
}
void pop()
{
if(front==null)
return;
if(front==rear)
{
front=null;
rear=null;
}
else
{
node* x=front;
front=x->nxt;
delete x;
}
}
int empty()
{
return front==null;
}
int _front()
{
if(front==null)
return 0;
else
return front->val;
}
};
int main()
{
queue q=queue();
q.push(1);
q.push(2);
q.pop();
q.push(3);
q.push(4);
q.push(5);
q.pop();
q.push(6);
while(!q.empty())
{
int x =q._front();
q.pop();
printf("%d\n",x);//3 4 5 6
}
}
数组实现
#include <cstdio>
#define null NULL
using namespace std;
struct queue
{
int* q;
int front;
int rear;
int maxsiz;
int siz;
queue(int _siz)
{
q=new int[_siz];
front=rear=siz=0;
maxsiz=_siz;
}
void push(int val)
{
if(siz==maxsiz)
{
printf("full\n");
return;
}
else
{
q[rear]=val;
rear=(rear+1)%maxsiz;
siz++;
}
}
int _front()
{
return q[front];
}
void pop()
{
front++;
siz--;
}
bool empty()
{
return siz==0;
}
};
int main()
{
queue q= queue(10);
q.push(1);
q.push(2);
q.pop();
q.push(3);
q.push(4);
q.push(5);
q.pop();
q.push(6);
while(!q.empty())
{
int x =q._front();
q.pop();
printf("%d\n",x);
}
}