/** * Beschreiben Sie hier die Klasse Stack. * * @author (Ihr Name) * @version (eine Versionsnummer oder ein Datum) */ public class Stack { private Node first; public Stack() { first = null; } public boolean isEmpty() { if (first == null) return true; return false; } public T top() { if (this.first == null) return null; return this.first.wert; } public void add(T val) { Node neu = new Node(); neu.wert = val; if (first == null) { first = neu; } else { Node current = first; while (current.next != null) { current = current.next; } current.next = neu; } } public void add(int n, T val) { if (n>= size()){ //überprüfung am anfang wenn n >= ist wie die länge, also zahlen die zu lang sind add(val); //wenn n zu groß dann hänge am ende an... return; // und beende die Methode } Node neu = new Node (); neu.wert = val; if (n == 0){ // Wenn Nachfolger an stelle 0 einfügen möchte dann neu.next = first;// Nachfolger auf bisher ersten(first) setzten first = neu;// Neuer Eintrag ist der neue Erste(first) return; //beenden } Node current = first; for (int i = 0; i < n-1; i++){ current = current.next; } neu.next =current.next; current.next = neu; } public boolean contains(T val) { Node current = first; while (current != null) { if (current.wert.equals(val)) return true; } return false; } public T remove(int n) { if (n >= size()) return null; //um fehler zu beheben: Parameter darf nicht größer als tatsächlicher Länge sein if ( n == 0){ // wenn Parameter 0 ist dann... T tmp = first.wert; // wert von first (=0) speichern first = first.next; //first "pfeil" auf den nächsten return tmp;//wert ausgeben } Node current = first; for (int i = 0; i < n-1; i++){ current = current.next; } T tmp = current.next.wert; // (Zwischenvariable um gelöschten Wert zu speichern) current.next = current.next.next; // Pfeil auf nächsten verschieben damit er nichr auf gelöschtem Zeigt return tmp; //gelöschten Wert ausgeben } public String toString(){ // glaub um halt alles schön auszugeben String result = ""; Node current = first; while (current != null){ result += current.wert + ", "; current = current.next; } return result; } }