#include <stdio.h>
#include <stdlib.h>
typedef void (*enqueue)(int);
typedef int (*dequeue)();
typedef int (*queueempty)();
#define N 10
int q1[N];
int head1 = 0, tail1 = 0;
// head must point to an empty space
// so queue's capacity is N - 1
void enqueue1(int e)
{
int t = (tail1 + 1) % N;
if (t == head1)
{
printf("queue1 overflow\n");
exit(1);
}
q1[t] = e;
tail1 = t;
}
int dequeue1()
{
if (queue1empty())
{
printf("queue1 empty\n");
exit(1);
}
head1 = (head1 + 1) % N;
return q1[head1];
}
int queue1empty()
{
if (head1 == tail1)
{
return 1;
}
return 0;
}
int q2[N];
int head2 = 0, tail2 = 0;
void enqueue2(int e)
{
int t = (tail2 + 1) % N;
if (t == head2)
{
printf("queue2 overflow\n");
exit(1);
}
q2[t] = e;
tail2 = t;
}
int dequeue2()
{
if (queue2empty())
{
printf("queue2 empty\n");
exit(1);
}
head2 = (head2 + 1) % N;
return q2[head2];
}
int queue2empty()
{
if (head2 == tail2)
{
return 1;
}
return 0;
}
// queue1 is main.
enqueue EN_M = enqueue1; // main
dequeue DE_M = dequeue1;
queueempty EMP_M = queue1empty;
enqueue EN_V = enqueue2; // vice
dequeue DE_V = dequeue2;
queueempty EMP_V = queue2empty;
void swap()
{
enqueue e1 = EN_M;
dequeue d1 = DE_M;
queueempty q1 = EMP_M;
EN_M = EN_V;
DE_M = DE_V;
EMP_M = EMP_V;
EN_V = e1;
DE_V = d1;
EMP_V = q1;
}
void push(int e)
{
if (!EMP_V())
{
while (!EMP_M())
{
EN_V(DE_M());
}
swap();
}
EN_V(e);
}
int pop()
{
if (!EMP_V())
{
return DE_V();
}
return DE_M();
}
int main()
{
/*
// test queue1
ENQUEUE = enqueue1;
DEQUEUE = dequeue1;
ENQUEUE(1);
ENQUEUE(2);
ENQUEUE(3);
ENQUEUE(4);
ENQUEUE(5);
ENQUEUE(6);
ENQUEUE(7);
ENQUEUE(8);
ENQUEUE(9);
printf("%d\n", DEQUEUE());
printf("%d\n", DEQUEUE());
printf("%d\n", DEQUEUE());
printf("%d\n", DEQUEUE());
printf("%d\n", DEQUEUE());
ENQUEUE(7);
ENQUEUE(8);
ENQUEUE(9);
printf("%d\n", DEQUEUE());
printf("%d\n", DEQUEUE());
printf("%d\n", DEQUEUE());
*/
push(1);
push(2);
push(3);
push(4);
push(5);
push(6);
push(7);
push(8);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
push(9);
push(10);
push(11);
push(12);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
push(13);
printf("%d\n", pop());
push(13);
push(13);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
return 0;
}
|