一个数组实现双栈c语言,双栈实现一队列/双队列实现一栈 C语言实现

#include

#include

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值