你好,我如何创建一个在列表开头添加元素的方法
。
我知道我必须在这里创建一个新的Pokeball
,将新的pokeball.next指向头部并将头部指向新的Pokeball,但我不知道该怎么做
我的列表现在看起来像这样:
Bulbasaur -> Squirtle
我想在开头添加 charmander
Charmander -> Bulbasaur -> Squirtle
调用方法时:d1.prepend(p3)
,它必须先经过 Trainer 类,然后经过 Pokeball
类,就像我的 addPokemon
一样方法谢谢
public class test {
public static void main(String[] args) {
Pokemon p1 = new Pokemon("Bulbasaur", "grass");
Pokemon p2 = new Pokemon("Squirtle", "water");
Pokemon p3 = new Pokemon("Charmander", "fire");
Trainer d1 = new Trainer("Pierre");
d1.addPokemon(p1);
d1.addPokemon(p2);
}
}
public class Pokemon {
private String name;
private String type;
private int niveau;
public Pokemon(String name, String type) {
this.name = name;
this.type = type;
this.niveau = (int) (Math.random() * (1 * 1 - 100) + 100);
}
}
public class Trainer {
public final String name;
private Pokeball head;
public Trainer(String name) {
this.name = name;
}
public void addPokemon(Pokemon pok) {
if (this.head != null) {
this.head.addPokemon(pok);
} else {
this.head = new Pokeball(pok);
}
}
public void prepend(Pokemon pok) {
this.head.prepend(pok);
}
}
public class Pokeball {
private Pokemon pok;
private Pokeball next;
public Pokeball(Pokemon pok) {
this.pok = pok;
}
public Pokeball(Pokemon pok, Pokeball next) {
this.pok = pok;
this.next = next;
}
public void addPokemon(Pokemon pok) {
Pokeball current = this;
while (current.next != null) {
current = current.next;
}
current.next = new Pokeball(pok);
}
public void prepend(Pokemon pok) {
}
}
最佳答案
您无法在 Pokeball
上调用 prepend
来在其后面附加某些内容,除非每个 Pokeball
也包含对前一个 Pokeball 的引用
.
解决方案实际上比这简单得多。只需将您的新 Pokeball
放在您的列表中即可:
public class Trainer {
public final String name;
private Pokeball head;
...
public void prepend(Pokemon pok) {
Pokeball newPokeball = new Pokeball(pok);
newPokeball.next = this.head;
this.head = newPokeball;
}
}
编辑: 另一个有趣的练习是尝试在列表中间添加一个 Sprite 球: 妙蛙种子 -> 小火龙 -> 杰尼龟
要做到这一点,你只需要从头部开始,直到找到你想要添加新的 Sprite 球为止。其余部分与上面非常相似。
public void addAfterPokeball(Pokemon theOneToInsertAfter, Pokemon pok) {
Pokeball newPokeball = new Pokeball(pok);
Pokeball tmp = head;
while (tmp != null && tmp.pok.name != theOneToInsertAfter.name) {
tmp = tmp.next;
}
if (tmp!=null){
newPokeball.next = tmp.next;
tmp.next = newPokeball;
} else {
//could not find the pokeball to insert after
}
}
关于java - 如何在链表的开头添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48886311/