按降序对单链表进行排序
Posted
技术标签:
【中文标题】按降序对单链表进行排序【英文标题】:Sort Single Linked List in descending order 【发布时间】:2016-10-16 19:57:23 【问题描述】:如何按分数降序显示此链接列表?当我在我的 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;
【问题讨论】:
听起来您需要一个最大优先级队列。有关如何执行此操作的示例,请参见此答案。 ***.com/questions/11003155/… 【参考方案1】:你为什么把 Score 当作一个字符串?
我假设分数为整数
下面是您可以在 ScoreList 类中包含的排序方法,它将按照玩家得分的降序对您的 LinkList 进行排序。
时间复杂度:O(nlogn) 空间复杂度:O(n)希望对你有帮助
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];
【讨论】:
以上是关于按降序对单链表进行排序的主要内容,如果未能解决你的问题,请参考以下文章