Advertisement
NetaK

queue_using_2_stacks

Apr 21st, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. import java.util.NoSuchElementException;
  2. import java.util.Stack;
  3.  
  4. public class Queue<T> {
  5.     Stack<T> pushStack;
  6.     Stack<T> pullStack;
  7.    
  8.     public Queue() {
  9.         this.pushStack = new Stack<T>();
  10.         this.pullStack = new Stack<T>();
  11.     }
  12.    
  13.     private void flush() {
  14.         while (!this.pushStack.empty()) {
  15.             T next = this.pushStack.pop();
  16.             this.pullStack.add(next);
  17.         }
  18.     }
  19.    
  20.     public void add(T elem) {
  21.         this.pushStack.add(elem);
  22.     }
  23.    
  24.     private T pop() {
  25.         if (!this.pullStack.empty()) {
  26.             return this.pullStack.pop();
  27.         }
  28.         this.flush();
  29.         if (!this.pullStack.empty()) {
  30.             return this.pullStack.pop();
  31.         }
  32.         return null;
  33.     }
  34.    
  35.     private T head() {
  36.         if (!this.pullStack.empty()) {
  37.             return this.pullStack.peek();
  38.         }
  39.         this.flush();
  40.         if (!this.pullStack.empty()) {
  41.             return this.pullStack.peek();
  42.         }
  43.         return null;
  44.     }
  45.    
  46.     public T poll() {
  47.         return this.pop();
  48.     }
  49.    
  50.     public T remove() {
  51.         T elem = this.pop();
  52.         if (elem != null) {
  53.             return elem;
  54.         }
  55.         throw new NoSuchElementException();
  56.     }
  57.    
  58.     public T peek() {
  59.         return this.head();
  60.     }
  61.    
  62.     public T element() {
  63.         T elem = this.head();
  64.         if (elem != null) {
  65.             return elem;
  66.         }
  67.         throw new NoSuchElementException();
  68.     }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement