如何按分数按照降序显示此链接列表?我需要它,当它在我的GUI中显示它按顶部的最高分排序,然后下降到底部的最低分?此外,我想知道是否有办法将条目限制为只有10.任何帮助将不胜感激!感谢。
public class ScoreList {
private Player head; //reference to the head of the list
private Player tail; //reference to the tail of the list
int count;
public ScoreList() {
count = 0;
head = null;
tail = null;
}
public int getCount() {
return count;
}
public int size() {
int count = 0;
Player p = head;
while(p != null) {
count++;
p = p.next;
}
return count;
}
//method to add an item to the list - append to the tail of the list
public void add(String name, String score) {
// Create Player object
Player newPlayer = new Player(name, score);
if (head == null) {
head = newPlayer;
tail = head;
count++;
}
else {
//append to the end of the list
tail.setNext(newPlayer);
tail = newPlayer;
count++;
}
if(size() > 10) {
Player currentPlayer = head;
for (int i = 0; i < 9; i++) {
currentPlayer = currentPlayer.next;
}
currentPlayer.next = null;
}
}
// end add method
//method to let the user get the data from a node in the list
public String getItem(int index) {
String result = "";
String name = "";
String score = "";
Player curName;
if (count > 0 && index == 0) {
//return the Player info at the head of the list
name = head.getName();
score = head.getScore();
}
else if (index > 0 && index < count) {
curName = head;
for (int i = 1; i <= index; i++) {
curName = curName.getNext();
}
name = curName.getName();
score = curName.getScore();
}
result = "Player: " + name + " Score: " + score;
return result;
}
//nested inner class
public class Player {
private String player;
private String score;
private Player next;
public Player() {
player = "";
score = "";
next = null;
}
public Player(String artist, String title) {
this.player = artist;
this.score = title;
next = null;
}
public String getName() {
return player;
}
public String getScore() {
return score;
}
public Player getNext() {
return next;
}
public void setArtist(String player) {
this.player = player;
}
public void setTitle(String score) {
this.score = score;
}
public void setNext(Player next) {
this.next = next;
}
}
}
答案 0 :(得分:0)
你为什么把分数作为一个字符串?
我假设得分为整数
下面的是您可以包含在ScoreList类中的排序方法,它将按照玩家得分的降序对您的LinkList进行排序。
希望这有帮助
public void sort() {
Player runner = head;
Player[] arr = new Player[size()];
int i = 0;
while (runner != null) {
arr[i++] = runner;
runner = runner.next;
}
Arrays.sort(arr, new Comparator<Player>() {
public int compare(Player o1, Player o2) {
if (Integer.parseInt(o1.getScore()) > Integer.parseInt(o2.getScore())) {
return -1;
} else if (Integer.parseInt(o1.getScore()) < Integer.parseInt(o2.getScore())) {
return 1;
} else {
return 0;
}
}
});
for (int j = 0; j < arr.length - 1; j++) {
arr[j].setNext(arr[j + 1]);
}
if (arr.length > 0) {
arr[arr.length - 1].setNext(null);
head = arr[0];
tail = arr[arr.length - 1];
}
}