你好我怎样才能在我的列表开头添加一个元素method
。
我知道我必须在这里创建一个新的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) {
}
}
答案 0 :(得分:1)
除非每个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 - >小水龟
要做到这一点,你只需要从头开始直到找到你想要添加新球的棒球。其余的与上面非常相似。
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
}
}
答案 1 :(得分:1)
我们的馆藏课程将为您提供帮助。如果你创建一个Pokemon的LinkedList,这支持addFirst()插入列表的头部。
List<Pokemon> list = new LinkedList<>();
//other pokemon inserted here
// ...
//insert new item at front of list
list.addFirst(newPokemon);
答案 2 :(得分:0)
我试着猜猜你想做什么。我想你试图实现自己的链式列表。
您需要实例化一个Pokeball并将列表的当前第一个元素添加为您刚创建的实例的下一个元素。我猜你的List对象包含对你的第一个元素的引用,它也需要更改。