你好,我怎样做一个method
,在列表的开头添加一个元素。
我知道我必须在这里创建一个新的Pokeball
,将new 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) {
}
}
最佳答案
除非每个prepend
都拥有对先前Pokeball
的引用,否则无法在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;
}
}
编辑:
另一个有趣的练习是尝试在列表中间添加一个pokeball:
Bulbasaur-> Charmander->松鼠
为此,您只需要从头开始,直到找到要在其后添加新球的pokeball。其余与上面非常相似。
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
}
}