Oppgave 2
@Override public int antall() { return antall; } @Override public boolean tom() { return antall == 0; } @Override public void nullstill() { Node<T> p = hode, q = null; while (p != null) { q = p.neste; p.neste = null; p.verdi = null; p = q; } hode = hale = null; antall = 0; } @Override public String toString() { StringBuilder s = new StringBuilder(); s.append('['); if (!tom()) { Node<T> p = hode; s.append(p.verdi); p = p.neste; while (p != null) // tar med resten hvis det er noe mer { s.append(',').append(' ').append(p.verdi); p = p.neste; } } s.append(']'); return s.toString(); }
Oppgave 3
public EnkeltLenketListe(T[] a) { this(); // alle variabelene er nullet // Finner den første i a som ikke er null int i = 0; for (; i < a.length && a[i] == null; i++); if (i < a.length) { Node<T> p = hode = new Node<>(a[i], null); // den første noden antall = 1; // vi har minst en node for (i++; i < a.length; i++) { if (a[i] != null) { p = p.neste = new Node<>(a[i], null); // en ny node antall++; } } hale = p; } }
Oppgave 4
public static void main(String... args) // hovedprogram { Liste<Integer> liste = new EnkeltLenketListe<>(); System.out.println("Antall i listen: " + liste.antall()); System.out.println("Listen inneholder: " + liste); for (int i = 0; i < 10; i++) liste.leggInn(i + 1); System.out.println("Antall i listen: " + liste.antall()); System.out.println("Listen inneholder: " + liste); liste.nullstill(); System.out.println("Antall i listen: " + liste.antall()); for (int i = 0; i < 10; i++) liste.leggInn(liste.antall()/2, i + 1); System.out.println("Antall i listen: " + liste.antall()); System.out.println("Listen inneholder: " + liste); } // main