Ubgrade 11.1

master
david 2023-01-11 11:10:41 +01:00
parent 8a8fbc4e93
commit a137bfc354
3 changed files with 82 additions and 29 deletions

View File

@ -5,31 +5,79 @@
* @author (Ihr Name)
* @version (eine Versionsnummer oder ein Datum)
*/
public class LinkedList
public class LinkedList<T>
{
public Node first;
public LinkedList(){
public Node<T> first;
public LinkedList(){
}
public void einfuegen (int neu) {
Node n = new Node(neu);//Neue Node mit Zahl "neu " anlegen
//Überprüfe ob die liste leer ist
if(first == null){
//setze neue node als erster Eintrag
first = n;
public void einfuegen (T neu) {
Node<T> n = new Node<T>(neu);//Neue Node mit Zahl "neu " anlegen
//Überprüfe ob die liste leer ist
if(first == null){
//setze neue node als erster Eintrag
first = n;
}
else {
Node<T> current = first;
while(current.next != null){
current = current.next;
}
current.setNext(n);
}
//current ist jetzt der letzte Eintrag
//setze neue Node als Nachfolger von bisher letztem Eintrag
}
else {
public int laenge(){
Node current = first;
while(current.next != null){
current = current.next;
int laenge = 0;
while(current != null){
current = current.next;
laenge++;
}
return laenge;
}
current.setNext(n);
public T getNteZahl(int n){
Node<T> current = first;
for(int i = 0; i<n; i++){
current = current.next;
}
return current.zahl;
}
//current ist jetzt der letzte Eintrag
//setze neue Node als Nachfolger von bisher letztem Eintrag
public void loesche(int n){
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 hinzufügen(int n, T wert){
Node<T> neu = new Node<T>(wert);
if(n==0){
neu.setNext(first);
first = neu;
}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;
}
}
}

View File

@ -5,14 +5,14 @@
* @author (Ihr Name)
* @version (eine Versionsnummer oder ein Datum)
*/
public class Node
public class Node<T>
{
public int zahl;
public T zahl;
public Node next;
public Node(int z){
public Node(T z){
zahl = z;
}
public void setNext(Node n){

View File

@ -7,8 +7,10 @@
*/
public class test
{
public void test(){
public static void test(){
Node<String> test = new Node<String>("Hallo");
Node<Integer> test2 = new Node<Integer>(5);
LinkedList liste = new LinkedList();
liste.einfuegen(5);
liste.einfuegen(6);
@ -16,7 +18,8 @@ public class test
liste.einfuegen(3);
liste.einfuegen(7);
liste.einfuegen(9);
liste.loesche(2);
liste.hinzufügen(8,"wirklich");
Node current = liste.first;
while(current != null){
@ -24,8 +27,10 @@ public class test
current = current.next;
}
System.out.println("Die Liste hat "+liste.laenge()+" Einträge. ");
}
}