为什么80%的码农都做不了架构师?>>>
思路:两个队列q1和q2,两个队列指针pusher和poper分别指向q1和q2,push时调用pusher->enqueue,然后将poper里的元素全部dequeue并enqueue到pusher,最后交换pusher和poper。
#include <iostream>class Queue
{int *array;int head, tail, size;Queue(Queue &&q) = delete;Queue(const Queue &q) = delete;Queue &operator=(const Queue &q) = delete;public:Queue(int n){size = n + 1;array = new int [size];head = 0;tail = 0;}~Queue(){if (array){delete [] array;array = NULL;size = -1;head = -1;tail = -1;}}bool enqueue(int x){if (full())return false;array[tail++] = x;if (tail >= size)tail = 0;return true;}bool dequeue(int &res){if (empty())return false;res = array[head++];if (head >= size)head = 0;return true;}bool empty(){return head == tail;}bool full(){return (tail + 1) % size == head;}
};class Stack
{Queue q1, q2, *pusher, *poper;int size;public:Stack(int n) : q1(n), q2(n){pusher = &q1;poper = &q2;}bool push(int x){if (poper->full())return false;pusher->enqueue(x);while (poper->dequeue(x))pusher->enqueue(x);Queue *tmp = pusher;pusher = poper;poper = tmp;return true;}bool pop(int &res){return poper->dequeue(res);}
};int main()
{int t;Queue queue(4);queue.enqueue(1);queue.dequeue(t);queue.enqueue(2);queue.dequeue(t);queue.enqueue(3);queue.enqueue(4);queue.enqueue(5);queue.enqueue(6);queue.enqueue(7);while (queue.dequeue(t))std::cout << t << std::endl;queue.enqueue(8);queue.enqueue(9);queue.enqueue(10);queue.enqueue(11);queue.enqueue(12);while (queue.dequeue(t))std::cout << t << std::endl;Stack stack(4);stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);while(stack.pop(t))std::cout << t << std::endl;return 0;
}