我使用链表来表示稀疏矩阵,其中链表仅保存非零元素及其在矩阵中的行和列,以便不浪费内存。
我需要能够根据行和列的顺序显示这些元素的位置。例如,包含 {data 5, row 2, col 0}、{data 8, row 0, col 2}、{data 1, row 0, col 1} 的矩阵将打印出:
0 1 1, 0 2 8, 2 0 5。
矩阵写为:
LinkedList<MatrixElement> matrix = new LinkedList<MatrixElement>();
元素类写为:
class MatrixElement { //Data object for each node in list, holds value and location
private int data;
private int row;
private int col;
public MatrixElement(int row, int col, int data){
this.data = data;
this.row = row;
this.col = col;
}
public int getData(){
return data;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
任何有关我应该如何对其进行排序以便最终打印的反馈将不胜感激。感谢您的帮助。
最佳答案
您可以按行然后按列排序,如下所示:
matrix.sort(Comparator.comparingInt(MatrixElement::getRow)
.thenComparingInt(MatrixElement::getCol));
关于java - 如何根据两个对象参数对对象链接列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673357/