Java链表问题
我一直在研究一个链表,但遇到了一点障碍。该列表应该是运动员对象的表示,其中包含他们的姓名和分数。运动员课程是提供给我的,因此我不应该改变它。我已经完成了比赛的大部分课程,但根据评分标准,我现在应该打印出名单中前三名的分数。我尝试过几种不同的方法,但都没有成功。有人知道我怎样才能做到这一点吗?下面是源代码,Competition和CompetitionDriver类是我开发的。顺便说一下,这是大学课程。感谢所有有建议的人
运动员。爪哇:
public class Athlete implements Comparable {
private String name;
private int score;
public Athlete (String n, int s) {
name = n;
score = s;
}
public int getScore() {
return score;
}
public String toString() {
return name;
}
public int compareTo(Object other) {
return (score - ((Athlete)other).getScore());
}
}
竞争。爪哇:
public class Competition {
private Athlete current;
private Competition next;
public Competition() {
current = null;
next = null;
}
public Competition(Athlete currentIn, Competition nextIn) {
current = currentIn;
next = nextIn;
}
public void addToEnd(Athlete input) {
if (current != null) {
Competition temp = this;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Competition(input, null);
}
else {
current = input;
}
}
public void print() {
Competition temp = this;
while(temp != null) {
System.out.println("\nAthlete name: "
+ temp.current.toString()
+ "\nAthlete score: "
+ temp.current.getScore());
temp = temp.next;
}
}
}
竞争河流。爪哇:
public class CompetitionDriver {
public static void main(String[] args) {
Competition competition = new Competition();
competition.addToEnd(new Athlete("Jane", 7));
competition.addToEnd(new Athlete("Mark", 9));
competition.addToEnd(new Athlete("Mary", 6));
competition.addToEnd(new Athlete("Eve", 2));
competition.addToEnd(new Athlete("Dan", 15));
competition.addToEnd(new Athlete("Adam", 4));
competition.addToEnd(new Athlete("Bob", 3));
competition.addToEnd(new Athlete("Kathy", 8));
competition.addToEnd(new Athlete("John", 5));
competition.addToEnd(new Athlete("Rob", 1));
competition.print();
competition.printTop();
}
}
# 1 楼答案
您有两个选择:
1)检查每个节点并确定前3名得分。(我不建议这样做,因为这需要在每个节点上记录前三名)
2)始终将链接列表按降序排序。这样,当您需要查找前三个节点时,可以从第一个节点开始,然后转到下两个节点。这也意味着在插入/删除列表时,您需要对列表进行排序。我建议调查一下Heap datastructure
# 2 楼答案
将以下代码用于:
竞争。爪哇:
还有河上的竞争。爪哇
然后运行它
# 3 楼答案
将此添加到您的班级竞赛中:
这适用于您给出的示例。希望它也适用于所有示例
编辑:别忘了将此方法添加到您的main中,就像这样:竞争。三强()强>