Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>Disclaimer: null values prohibited (just like ArrayDeque), and not rigorously tested.</em> <br/><br/></p> <pre class="lang-java prettyprint-override"><code>import java.util.ArrayDeque; public class PessimisticStack&lt;T extends Comparable&lt;? super T&gt;&gt; { private class Entry { private Entry(T t, T minNow) { this.t = t; this.minNow = minNow; } private final T t; private final T minNow; } private final ArrayDeque&lt;Entry&gt; deque; public PessimisticStack() { deque = new ArrayDeque&lt;Entry&gt;(); } public PessimisticStack(int initialCapacity) { deque = new ArrayDeque&lt;Entry&gt;(initialCapacity); } public void push(T t) { if (t == null) throw new NullPointerException(); Entry entry = null; if (deque.isEmpty()) { entry = new Entry(t, t); } else { T prevMinimum = deque.peek().minNow; T newMinimum = null; if (t.compareTo(prevMinimum) &lt; 0) { newMinimum = t; } else { newMinimum = prevMinimum; } entry = new Entry(t, newMinimum); } deque.push(entry); } public T pop() { return deque.pop().t; } public T getMinimum() { Entry entry = deque.peek(); return (entry == null ? null : entry.minNow); } } </code></pre> <p><strong>Example Usage</strong></p> <pre><code>PessimisticStack&lt;String&gt; stack = new PessimisticStack&lt;String&gt;(); stack.push("Zebra"); stack.push("Elephant"); stack.push("Bryan"); stack.push("Adam"); stack.push("Calvin"); String calvin = stack.pop(); // "Adam" System.err.println(stack.getMinimum()); stack.push("Aaron"); // "Aaron" System.err.println(stack.getMinimum()); String aaron = stack.pop(); // "Adam" System.err.println(stack.getMinimum()); String adam = stack.pop(); // "Bryan" System.err.println(stack.getMinimum()); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload