【发布时间】:2018-02-24 12:30:22
【问题描述】:
您好,我正在创建自己的链接列表,但没有实现 java.util.linkedlist
我想创建一个递归添加方法:
- 应该添加一个级别介于低级别和高级别之间的口袋妖怪 像这样的东西:
Bulbasaur(5) -> Squirtle(15) -> Charmander(20)
然后添加等级为6的(鸽子):
Bulbasaur(5) -> 鸽子(6) -> Squirtle(15) -> Charmander(20)
添加鸽子是我苦苦挣扎的部分
到目前为止,我已经设法对它们进行了排序,因为我一直在将它们从最小到最大添加:
d1.addPokemon(p1); // 5级
d1.addPokemon(p2); // 15级
d1.addPokemon(p3); //20级
d1.addPokemon(p4); // level 6 - 不加,我的方法有问题不知道改什么
谢谢
public class Trainer{
public final String name;
private Pokeball head;
public Trainer(String name) {
this.name = name;
}
public void display() {
System.out.print(this.name + " : ");
this.head.display();
}
public void addPokemon(Pokemon pok) {
if (this.head != null) {
this.head.addPokemon(this.head, pok);
} else {
this.head = new Pokeball(pok);
}
}
}
public class Pokeball {
private Pokemon pok;
private Pokeball next;
public Pokeball(Pokemon pok) {
this.pok = pok;
}
public Pokeball addPokemon(Pokeball current, Pokemon pok) {
if (current == null) {
return null;
}
if (current.pok.getLevel() > pok.getLevel()) {
Pokeball newPokeball = new Pokeball(pok);
newPokeball.next = current;
return newPokeball;
}
// if next is null add it to next
if (current.next == null) {
current.next = new Pokeball(pok);
}
// if next is not null and value is between two sequences add it between
else if (pok.getLevel() > current.pok.getLevel() && pok.getLevel() <= current.next.pok.getLevel()) {
Pokeball newPokeball = new Pokeball(pok);
newPokeball.next = current.next;
current.next = newPokeball;
}
// If value is not between call recursion again
else {
addPokemon(current.next, pok);
}
return current;
}
public class Pokemon {
private String name;
private int level;
public Pokemon(String name, int level) {
this.name = name;
this.level = level;
}
public void display() {
System.out.println();
System.out.print(this.name + " : " + this.level);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
public class test {
public static void main(String[] args) {
Pokemon p1 = new Pokemon("Bulbasaur", 5);
Pokemon p2 = new Pokemon("Squirtle", 15);
Pokemon p3 = new Pokemon("Charmander", 20);
Pokemon p4 = new Pokemon("Pigeon", 6);
Trainer t1 = new Trainer("Pierre");
t1.addPokemon(p1);
t1.addPokemon(p2);
t1.addPokemon(p3);
t1.addPokemon(p4);
t1.display();
// prints :
Pierre :
Bulbasaur : 5
Squirtle : 15
Charmander : 20
// But pigeon is not here ! :(
}
}
【问题讨论】:
-
我没有看到 Dresseur 的 addPokemon()
-
啊,是的,对不起,我已经编辑了我的变量是法语的,我忘了改这个
-
以递归形式实现
add方法是否有任何义务?因为你总是有一个排序列表,当你想找到添加新口袋妖怪的正确位置时,你可以在没有递归的情况下非常清楚地做到这一点。 -
我更新了答案,但是如果新的Pokeball是最小的级别,它是在Trainer类的addpokemon方法中添加的
-
@Blebhebhe 实际上它不符合 SO 规则,因为您要求使用递归方法,所以我的回答是错误的。
标签: java sorting linked-list