代码:
#include <iostream>
#include <string.h>
#define N 3
typedef struct Queue
{
int a[N];
int head,tail;
}Queue;
void show(Queue* p)
{
for(int i=0;i<N;i++)
{
std::cout << p->a[i] << ‘ ‘;
}
}
void init(Queue* p)
{
memset(p->a, 0, sizeof(int)*N);
p->head = 0;
p->tail = 0;
}
void push(Queue* p,int val)
{
++p->tail;
if(p->tail > N-1)
{
std::cout << "队列溢出" << ‘ ‘;
}
else
{
for (int i = p->tail; i >0; i--)
{
*(p->a + i) = *(p->a + i - 1);
}
/*
for(int i = p->tail;i > 0;i--)
{
p->a[i] = p->a[i-1];
std::cout << p->a[i] << ‘ ‘;
}
*/
p->a[0] = val;
}
}
int pop(Queue* p)
{
if(p->tail == -1)
{
std::cout << "队列为空!!" << ‘ ‘;
}
else
{
int tem = p->a[p->tail];
--p->tail;
std::cout << tem << ‘ ‘;
return tem;
}
return 1;
}
int main()
{
Queue q;
init(&q);
std::cout << "push操作:" << ‘\n‘;
for(int i=1;i<N;i++)
{
push(&q,i);
}
show(&q);
std::cout << ‘\n‘;
std::cout << "pop操作:" <<‘\n‘;
for(int i=0;i<N;i++)
{
pop(&q);
}
return 0;
}
测试结果:
用数组实现队列(C++)
原文:https://www.cnblogs.com/shiheyuanfang/p/13582476.html