| 1 | import java.lang.reflect.Array; |
| 2 | |
| 3 | /** |
| 4 | * |
| 5 | */ |
| 6 | public class Pile<E> { |
| 7 | private E[] array; |
| 8 | private int array_size; |
| 9 | private int stack_head_index; |
| 10 | |
| 11 | /** |
| 12 | * set the size of the internal array |
| 13 | * @param int size the size of the array |
| 14 | */ |
| 15 | public void setSize(int size) { |
| 16 | array_size = size; |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * get the size of the internal array |
| 21 | * @return the integer size of the internal array |
| 22 | */ |
| 23 | public int getSize() { |
| 24 | return array_size; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * set the stack head index |
| 29 | * @param int index the stack head index |
| 30 | */ |
| 31 | public void setHeadIndex(int index) { |
| 32 | stack_head_index = index; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * get the stack head current index |
| 37 | * @return the integer stack head index |
| 38 | */ |
| 39 | public int getHeadIndex() { |
| 40 | return stack_head_index; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * [Pile description] |
| 45 | * @param int size [description] |
| 46 | */ |
| 47 | @SuppressWarnings("unchecked") |
| 48 | Pile(int size) { |
| 49 | array = (E[])new Object[size]; |
| 50 | setSize(size); |
| 51 | setHeadIndex(0); |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * [Pile description] |
| 56 | * @param int size [description] |
| 57 | */ |
| 58 | @SuppressWarnings("unchecked") |
| 59 | Pile(Class<E[]> cl, int size) { |
| 60 | array = (E[])Array.newInstance(cl, size); |
| 61 | setSize(size); |
| 62 | setHeadIndex(0); |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * [empiler description] |
| 67 | * @param int value [description] |
| 68 | */ |
| 69 | public void empiler(E value) { |
| 70 | if (!plein()) { |
| 71 | array[stack_head_index] = value; |
| 72 | stack_head_index++; |
| 73 | } else { |
| 74 | System.out.println("La pile est pleine"); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * [depiler description] |
| 80 | * @return [description] |
| 81 | */ |
| 82 | public E depiler() { |
| 83 | if (!vide()) { |
| 84 | stack_head_index--; |
| 85 | return array[stack_head_index]; |
| 86 | } else { |
| 87 | return null; |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * [plein description] |
| 93 | * @return [description] |
| 94 | */ |
| 95 | private boolean plein() { |
| 96 | return (getHeadIndex() >= getSize()); |
| 97 | } |
| 98 | |
| 99 | /** |
| 100 | * [vide description] |
| 101 | * @return [description] |
| 102 | */ |
| 103 | private boolean vide() { |
| 104 | return (getHeadIndex() == 0); |
| 105 | } |
| 106 | |
| 107 | /** |
| 108 | * [afficher description] |
| 109 | */ |
| 110 | public void afficher() { |
| 111 | for (int i = 0; i < getHeadIndex(); i++) { |
| 112 | System.out.println("element " + i + " " + array[i]); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | } |