Ciao a tutti!
Ho creato una classe CodaConPrioritaHeap che implementa l'interfaccia CodaConPriorita che contiene i soliti metodi come inserisci, primo e cambiaPriorita. Voglio stampare l'intera coda, come faccio? Non posso scorrerla come fosse un array...
Posto il mio codice..
Graziecodice:[SIZE=1.5] public class CodaConPrioritaHeap implements CodaConPriorita { private class ElemConPrior { String elem; double prior; public ElemConPrior(String el, double p) { elem = el; prior = p; } } private ElemConPrior[] heap; private int indiceUltimo; private Hashtable<String, Integer> posizione = new Hashtable<String, Integer>(); public CodaConPrioritaHeap(int n) { heap = new ElemConPrior[n + 1]; indiceUltimo = 0; } public boolean eVuota() { if(indiceUltimo == 0) return true; return false; } public void inserisci(String el, double p) { if(indiceUltimo == heap.length - 1) ingrandisci(); heap[++indiceUltimo] = new ElemConPrior(el, p); moveUp(indiceUltimo); } private void ingrandisci() { int lung = heap.length * 2; ElemConPrior[] heapNew = new ElemConPrior[lung]; for(int i = 0; i < heap.length; i++) heapNew[i] = heap[i]; this.heap = heapNew; } private void moveUp(int i) { if(i > indiceUltimo) throw new IllegalArgumentException(); ElemConPrior eP = heap[i]; while(i > 1 && (eP.prior < heap[i/2].prior)) { heap[i] = heap[i/2]; posizione.put(heap[i].elem, i); i = i/2; } heap[i] = eP; posizione.put(eP.elem, i); } public String primo() { if(eVuota() == true) throw new IllegalArgumentException(); return heap[1].elem; } public String estraiPrimo() { if(indiceUltimo == 0) throw new IllegalArgumentException(); String primo = heap[1].elem; ElemConPrior ultimo = heap[indiceUltimo]; heap[indiceUltimo--] = null; if(indiceUltimo > 0) { heap[1] = ultimo; moveDown(1); } return primo; } private void moveDown(int i) { if(i > indiceUltimo) throw new IllegalArgumentException(); ElemConPrior eP = heap[i]; int j; while((j = 2*i) <= indiceUltimo) { if(j + 1 <= indiceUltimo && heap[j + 1].prior < heap[j].prior) j++; if(eP.prior <= heap[j].prior) break; heap[i] = heap[j]; i = j; } heap[i] = eP; } public void cambiaPriorita(String s, double p) { int i = posizione.get(s); cambiaPriorita(i, p); } private void cambiaPriorita(int i, double p) { if(i > indiceUltimo) throw new IllegalArgumentException(); heap[i].prior = p; moveDown(i); moveUp(i); } } [/SIZE]

Rispondi quotando