0002_Second push, added[add, insert(not working), remove, toString] for MyList, added[toString] for Pair, added[toString] for MyListElement

This commit is contained in:
WickedJack99
2022-07-01 11:51:55 +02:00
parent 49e78e2332
commit 29a1868992
5 changed files with 87 additions and 1 deletions

10
Main.java Normal file
View File

@@ -0,0 +1,10 @@
public class Main {
public static void main(String[] args) {
MyList list = new MyList();
list.add(new Pair(2,2));
list.remove(1);
list.insert(new Pair(3,3), 0);
System.out.println(list.toString());
}
}

View File

@@ -2,6 +2,69 @@ public class MyList {
public MyListElement first;
public MyList() {
first = new MyListElement();
first = null;
}
//Adds elem to list.
public void add(Pair pair) {
MyListElement elem = new MyListElement(pair, null);
//Case 1: List is empty
if (this.first == null) {
this.first = elem;
//Case 2: List is not empty
} else {
MyListElement node = this.first;
while (node.next != null) {
node = node.next;
}
node.next = elem;
}
}
//Inserts elem at index.
public void insert(Pair pair, int index) {
MyListElement node = this.first;
MyListElement pre = this.first;
if (index == 0) {
this.first = new MyListElement(pair, node);
} else {
int i = 1;
while ((index != i) && (node.next != null)) {
pre = node;
node = node.next;
i++;
}
}
}
//Removes element with key from list.
public void remove(Object key) {
//Case 1: Element to remove is first
if (this.first.data.key == key) {
this.first = this.first.next;
//Case 2: Element to remove is not first
} else {
MyListElement node = this.first;
MyListElement pre = this.first;
while ((node.next != null) && (node.data.key != key)) {
pre = node;
node = node.next;
if (node.data.key == key) {
pre.next = node.next;
}
}
}
}
//Return MyList as String.
@Override
public String toString() {
String listAsString = "";
MyListElement node = this.first;
while (node != null) {
listAsString += (node.data.toString() + ", ");
node = node.next;
}
return listAsString;
}
}

View File

@@ -11,4 +11,9 @@ public class MyListElement {
this.data = data;
this.next = next;
}
@Override
public String toString() {
return this.data.toString();
}
}

View File

@@ -11,4 +11,9 @@ public class Pair {
this.key = key;
this.data = data;
}
@Override
public String toString() {
return ("(" + this.key.toString() + "," + this.data.toString() + ")");
}
}

3
sort_algorithms.java Normal file
View File

@@ -0,0 +1,3 @@
public class sort_algorithms {
}