91 lines
2.3 KiB
Java
91 lines
2.3 KiB
Java
public class LinkedList<T>
|
|
{
|
|
public Node<T> first;
|
|
|
|
public LinkedList() {
|
|
}
|
|
|
|
public void einfuegen(T neu) {
|
|
Node n = new Node<T>(neu); // Neue Node mit Zahl "neu" anlegen
|
|
|
|
// Überprüfe, ob Liste leer
|
|
if (first == null) {
|
|
// setze neue Node als ersten Eintrag
|
|
first = n;
|
|
} else {
|
|
Node<T> current = first;
|
|
|
|
// gehe zum letzten Eintrag
|
|
while (current.next != null) {
|
|
current = current.next;
|
|
}
|
|
|
|
// current ist jetzt der letzte Eintrag
|
|
// setze neue Node als Nachfolger von bisher letzem Eintrag
|
|
current.setNext(n);
|
|
}
|
|
}
|
|
|
|
public int laenge() {
|
|
Node<T> current = first;
|
|
int laenge = 0;
|
|
|
|
while (current != null) {
|
|
current = current.next;
|
|
laenge++;
|
|
}
|
|
|
|
return laenge;
|
|
}
|
|
|
|
public T getNtenWert(int n) {
|
|
Node<T> current = first;
|
|
|
|
for (int i=0; i<n; i++) {
|
|
current = current.next;
|
|
}
|
|
|
|
return current.wert;
|
|
}
|
|
|
|
public void loesche(int n) {
|
|
if (n == 0) {
|
|
first = first.next;
|
|
} else {
|
|
Node<T> current = first;
|
|
|
|
// gehe an den Vorgänger des zu löschenden Eintrags
|
|
for (int i=0; i<n-1; i++) {
|
|
current = current.next;
|
|
}
|
|
|
|
// Setze Übernächsten Eintrag als Nachfolger
|
|
current.next = current.next.next;
|
|
}
|
|
}
|
|
|
|
public void einfuegen(int n, T wert) {
|
|
// Neue Node anlegen
|
|
Node<T> neu = new Node<T>(wert);
|
|
|
|
if (n == 0) {
|
|
// Setze Nachfolger auf bisherigen Start
|
|
neu.setNext(first);
|
|
// Setze neuen Start auf neues Element
|
|
first = neu;
|
|
} else {
|
|
Node<T> current = first;
|
|
// gehe an den Vorgänger
|
|
for (int i=0; i<n-1; i++) {
|
|
current = current.next;
|
|
}
|
|
|
|
// ändere neu.next auf current.next
|
|
neu.setNext(current.next);
|
|
|
|
// ändere current.next auf neu
|
|
current.setNext(neu);
|
|
}
|
|
}
|
|
}
|