Stack.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-3.5.0).
03  * Copyright (c) 2007-2016 Franz Wilhelmstötter
04  *
05  * Licensed under the Apache License, Version 2.0 (the "License");
06  * you may not use this file except in compliance with the License.
07  * You may obtain a copy of the License at
08  *
09  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author:
18  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19  */
20 package org.jenetics.internal.collection;
21 
22 import java.util.function.Consumer;
23 
24 /**
25  * Minimal implementation of stack data-structure. {@code Null} values are not
26  * permitted, but not checked.
27  *
28  * <pre>{@code
29  * final Stack<Integer> stack = new Stack<>();
30  * for (int i = 0; i &lt; 10; ++i) {
31  *     stack.push(i);
32  * }
33  *
34  * for (Integer i = stack.pop(); i != null; i = stack.pop()) {
35  *     System.out.println(i);
36  * }
37  * }</pre>
38  *
39  * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
40  * @version 2.0 &mdash; <em>$Date$</em>
41  * @since 2.0
42  */
43 public final class Stack<T> {
44 
45     private Node<T> _tail = null;
46 
47     public int length = 0;
48 
49     public void push(final T value) {
50         _tail = new Node<>(value, _tail);
51         ++length;
52     }
53 
54     public T pop() {
55         T value = null;
56         if (_tail != null) {
57             value = _tail._value;
58             _tail = _tail._previous;
59             --length;
60         }
61 
62         return value;
63     }
64 
65     public void popAll(final Consumer<T> consumer) {
66         for (T element = pop(); element != null; element = pop()) {
67             consumer.accept(element);
68         }
69     }
70 
71     public void clear() {
72         _tail = null;
73         length = 0;
74     }
75 
76     private static final class Node<T> {
77         final T _value;
78         final Node<T> _previous;
79 
80         Node(final T value, final Node<T> previous) {
81             _value = value;
82             _previous = previous;
83         }
84     }
85 }