La prima cosa che voglio postare è un'implementazione della struttura dati astratta STACK.
INTERFACCIA:
Codice:
package strutture_dati;
/**
* <p>Title: Stack</p>
* <p>Description: Interfaccia Stack</p>
*/
public interface Stack {
// Restituisce il numero degli elementi nello stack
public int size();
// Restituisce true se lo stack è vuoto, false altrimenti
public boolean isEmpty();
// Restituisce l'elemento al top dello stack.
// Se lo stack è vuoto lancia l'eccezione StackEmptyException
public Object top() throws StackEmptyException;
// Inserisce un elemento di tipo Object al top dello stack
public void push (Object element);
// Rimuove l'elemento al top dello stack. Restituisce l'elemento eliminato
// Se lo stack è vuoto lancia l'eccezione StackEmptyException
public Object pop() throws StackEmptyException;
}
ECCEZIONE:
Codice:
package strutture_dati;
/**
* <p>Title: StackEmptyException</p>
* <p>Description: Eccezione</p>
*/
public class StackEmptyException extends RuntimeException {
public StackEmptyException(String err) {
super(err);
messaggio = err;
}
public void notifica () {
System.out.println(messaggio);
}
private String messaggio;
}
IMPLEMENTAZIONE INTERFACCIA:
Codice:
package strutture_dati;
/**
* <p>Title: ArrayStack</p>
* <p>Description: Implementazione interfaccia Stack</p>
*/
public class ArrayStack implements Stack {
public ArrayStack (){
array = new Object[CAPACITY];
}
public int size() {
return topStack;
}
public boolean isEmpty() {
if (topStack == -1) return true;
else return false;
}
public Object top () throws StackEmptyException {
if (topStack == -1) throw new StackEmptyException("Lo stack è vuoto!");
return array[topStack];
}
public void push (Object element) {
topStack ++;
if (topStack == CAPACITY) { // inizio procedura di espansione array
int CAPACITY = CAPACITY + CAPACITY;
array2 = new Object[CAPACITY];
for (int i=0 ; i<CAPACITY ; i++) {
array2[i] = array[i];
}
array = array2;
} // fine procedura di espansione array
array[topStack]=element;
}
public Object pop () throws StackEmptyException {
if (topStack == -1) throw new StackEmptyException("Lo stack è vuoto!");
topStack --;
return array[topStack+1];
}
private Object[] array;
private Object[] array2;
public int CAPACITY = 1024;
private int topStack=-1;
}