双端队列的c语言实现
#include <stdbool.h>
#include <stdio.h>
/*
顺序队列存在假溢出问题--> 使用顺序循环队列解决
双端队列:
头 -- 尾
*/
#define SIZE 512
int queue[512];
int head;
int tail;
// (先进先出)
void push_front(int data)
{
queue[tail] = data;
tail = (tail + 1) % SIZE; // 核心
}
int pop_back()
{
int result = queue[head];
head = (head + 1) % SIZE;
return result;
}
//
void push_back(int data)
{
head = (head - 1 + SIZE) % SIZE;
queue[head] = data;
}
int pop_front()
{
tail = (tail - 1 + SIZE) % SIZE; // 找到出的元素 // +size 是考虑到负数的情况
return queue[tail];
}
bool empty()
{
return head == tail;
}
bool full()
{
return head == (tail + 1) % SIZE;
}
int main(void)
{
for (int i = 0; i < 3; i++)
{
if (!full())
{
push_front(i);
}
}
while (!empty())
{
printf("%d\n", pop_back());
}
return 0;
}
运行结果: