2014-09-05 67 views
0

我怎樣才能排序這個列表(降序)?它增加了數字,但按升序排序,但我希望它下降(不使用任何外部庫或任何東西)。我試圖弄清楚,但沒有拿出任何東西。排序一個列表(降序)

private void addNewElement() 
{ 
//getting the input 
System.out.print("Please type the number to be added to the list: "); 

Integer newValue = null; 
while(newValue == null) 
{ 
    try 
    { 
     newValue = Integer.parseInt(userInput.nextLine()); 
    } 
    catch (final Exception e) 
    { 
     System.out.println("Wrong value. Please insert new value."); 
    } 
} 

//creating new element based on the input 
MyListElement newElement = new MyListElement(newValue); 

//if not first 
if (firstElement != null) 
{ 
    placeElementInList(newElement); 
} 
else 
{ 
    firstElement = newElement; //if first 
} 
} 

//if not first 
private void placeElementInList(final MyListElement newElement) 
{ 
//if smaller than first 
if (newElement.value < firstElement.value) 
{ 
    newElement.nextElement = firstElement; //new points to first 
    firstElement = newElement;    //and becomes first 
} 
else 
{ 
    MyListElement previousElement = firstElement; //have to remember previous element 
    MyListElement elementInList = firstElement.nextElement; //currently checked. 
    while (elementInList != null) 
    { 
     if (newElement.value < elementInList.value) //if new element is smaller that currently checked 
     { 
      break; //break - put it in current position. 
     } 
     previousElement = elementInList; //if not, move forward, substitute variables 
     elementInList = elementInList.nextElement; 
    } 
    previousElement.nextElement = newElement; //set the new element at the proper position 
    newElement.nextElement = elementInList; // 
} 

}

+3

使用'Collections.sort'和'Comparator'。 – Mena 2014-09-05 18:22:56

+1

降序與升序相同,除非您翻轉標誌。您應該可以通過更改一行代碼來更改另一個。 – 2014-09-05 18:24:40

+0

'if(newElement.value> elementInList.value)'... – R2B2 2014-09-05 18:25:28

回答

0

有它降序排序,只需翻轉你所有的比較,從運營商到<>,例如

if (newElement.value > firstElement.value) 
+0

好吧,但是如果我應該在列表已經完成時將其降序排序呢?我的意思是,當時我要打印它。遵循: MyListElement elementInList = firstElement; (elementInList!= null) { System.out.print(elementInList.value +「,」); elementInList = elementInList.nextElement; } – user3816423 2014-09-05 18:38:24

+0

您可以通過交換第一個和最後一個元素,第二個元素和倒數第二個元素等來反轉列表,直到到達列表中間。 – rgettman 2014-09-05 18:40:03

+0

我應該使用while循環嗎?對不起,我很困惑 – user3816423 2014-09-05 18:42:19