Stack.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-2.0.2).
03  * Copyright (c) 2007-2014 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.util;
21 
22 /**
23  * Minimal implementation of stack data-structure. {@code Null} values are not
24  * permitted, but not checked.
25  *
26  * [code]
27  * final Stack<Integer> stack = new Stack<>();
28  * for (int i = 0; i < 10; ++i) {
29  *     stack.push(i);
30  * }
31  *
32  * for (Integer i = stack.pop(); i != null; i = stack.pop()) {
33  *     System.out.println(i);
34  * }
35  * [/code]
36  *
37  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
38  @version 2.0 &mdash; <em>$Date: 2014-03-28 $</em>
39  @since 2.0
40  */
41 public final class Stack<T> {
42 
43     private Node<T> _tail = null;
44 
45     public int length = 0;
46 
47     public void push(final T value) {
48         _tail = new Node<>(value, _tail);
49         ++length;
50     }
51 
52     public T pop() {
53         T value = null;
54         if (_tail != null) {
55             value = _tail._value;
56             _tail = _tail._previous;
57             --length;
58         }
59 
60         return value;
61     }
62 
63 
64     private static final class Node<T> {
65         final T _value;
66         final Node<T> _previous;
67 
68         Node(final T value, final Node<T> previous) {
69             _value = value;
70             _previous = previous;
71         }
72     }
73 }