Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.NoSuchElementException;
- import java.util.Stack;
- public class Queue<T> {
- Stack<T> pushStack;
- Stack<T> pullStack;
- public Queue() {
- this.pushStack = new Stack<T>();
- this.pullStack = new Stack<T>();
- }
- private void flush() {
- while (!this.pushStack.empty()) {
- T next = this.pushStack.pop();
- this.pullStack.add(next);
- }
- }
- public void add(T elem) {
- this.pushStack.add(elem);
- }
- private T pop() {
- if (!this.pullStack.empty()) {
- return this.pullStack.pop();
- }
- this.flush();
- if (!this.pullStack.empty()) {
- return this.pullStack.pop();
- }
- return null;
- }
- private T head() {
- if (!this.pullStack.empty()) {
- return this.pullStack.peek();
- }
- this.flush();
- if (!this.pullStack.empty()) {
- return this.pullStack.peek();
- }
- return null;
- }
- public T poll() {
- return this.pop();
- }
- public T remove() {
- T elem = this.pop();
- if (elem != null) {
- return elem;
- }
- throw new NoSuchElementException();
- }
- public T peek() {
- return this.head();
- }
- public T element() {
- T elem = this.head();
- if (elem != null) {
- return elem;
- }
- throw new NoSuchElementException();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement