我在我的程序中創建了我自己的LinkedList(不是java.util)的卡片。對作爲整數對的對象進行排序
每個卡是由2整數對象 - 第一個是一個卡(從1到13)的值,第二個是一個卡(從0到3)的顏色。
名單是隨機產生的,並在創建列表時的值是0
現在我想升級我加入卡的方法對它們進行排序,同時增加。 首先按價值,然後按顏色。
這裏是我的代碼看起來像現在:
public class Lista {
private Element pocz; //start
public int rozmiar;
public Lista() {
boolean zrobione = false;
while (zrobione != true) {
Karta karta = new Karta();
if (karta.getWartosc() == 0) {
zrobione = true;
} else {
this.dodaj(karta);
}
}
}
public void dodaj(Karta k) {
if (pocz == null) {
pocz = new Element(k);
}
Element pom = new Element(k);
Element obecny = pocz;
if (obecny != null) {
while (obecny.getNext() != null) {
obecny = obecny.getNext();
}
obecny.setNext(pom);
}
rozmiar++;
}
我一直在想一個解決方案,頗有幾分喜歡的東西來到了:
public void dodaj(Karta k){
if(rozmiar == 0) {
if (pocz == null) {
pocz = new Element(k);
}
Element pom = new Element(k);
Element obecny = pocz;
if (obecny != null) {
while (obecny.getNext() != null) {
obecny = obecny.getNext();
}
obecny.setNext(pom);
}
rozmiar++;
}
else{
Element pom = new Element(k);
Element obecny = pocz;
boolean znalezione = false;
if(obecny != null && !znalezione){
while(obecny.getNext() != null && !znalezione){
if(obecny.getKarta().wartosc < obecny.getNext().getKarta().wartosc) {
obecny.setNext(pom);
znalezione = true;
}
else if(obecny.getKarta().wartosc == obecny.getNext().getKarta().wartosc){
if(obecny.getKarta().kolor < obecny.getNext().getKarta().kolor){
obecny.setNext(pom);
znalezione = true;
}
else if(obecny.getKarta().kolor == obecny.getNext().getKarta().kolor){
obecny.setNext(pom);
znalezione = true;
}
else{
obecny = obecny.getNext();
obecny.setNext(pom);
znalezione = true;
}
}
else{
obecny = obecny.getNext();
obecny.setNext(pom);
znalezione = true;
}
}
}
rozmiar++;
}
}
但這種方法使我的清單隻包含2張卡片,我不確定它是否可以使用... 對不起英文名稱的變量和類別。
什麼,我想實現舉例:
Before sorting
11 2
5 3
2 3
13 0
1 2
5 2
1 1
5 1
After sorting
1 1
1 2
2 3
5 1
5 2
5 3
11 2
13 0
rozmiar
是List的大小
wartosc
是卡片的價值
kolor
是卡
dodaj
意味着色彩 「添加」
問題是我的任務是要做到這一點,而不使用的compareTo。我知道,我知道它的愚蠢,但... – Szouter