E pop_front() { if (outbox.empty()) { while (!inbox.empty()) { E tmp = inbox.top(); outbox.push(tmp); inbox.pop(); } } size--; E tmp = outbox.top(); outbox.pop(); return tmp; } };
intmain() { Queue<int> que; //push 01234 for (int i = 0; i < 5; i++) { que.push_back(i); } //pop 012 for (int i = 0; i < 3; i++) { cout << que.pop_front() << endl; } //push 78 for (int i = 7; i < 9; i++) { que.push_back(i); } //pop all left elements (3478) int len = que.size; for (int i = 0; i < len; i++) { cout << que.pop_front() << endl; }
//Linked Node template <typename E> classNode { public: E data; structNode<E> *next; Node<E>() { next = NULL; }
Node(E it, Node<E> *_next) { data = it; next = _next; } }; //Linked Based Stack template <typename E> classStack { private: Node<E> *head; int size; voidinit() { head = new Node<E>; size = 0; } public: Stack() { init(); } boolempty() { return size == 0; } E top() { return head->data; } voidpush(E it) { head = new Node<E>(it, head); size++; } E pop() { E tmp = top(); size--; Node<E> *temphead = head; head = head->next; delete temphead; return tmp; } }; //Queue implement template <typename E> classQueue { private: Stack<E> inbox; Stack<E> outbox;
public: int size = 0;
voidpush_back(E it) { inbox.push(it); size++; }
E pop_front() { if (outbox.empty()) { while (!inbox.empty()) { outbox.push(inbox.pop()); } } size--; return outbox.pop(); } };
intmain() { Queue<int> que; //push 01234 for (int i = 0; i < 5; i++) { que.push_back(i); } //pop 012 for (int i = 0; i < 3; i++) { cout << que.pop_front() << endl; } //push 78 for (int i = 7; i < 9; i++) { que.push_back(i); } //pop all left elements (3478) int len = que.size; for (int i = 0; i < len; i++) { cout << que.pop_front() << endl; }