2014-05-04 27 views
0

我遇到了一些困難。我想修改下面這段代碼來對Person類型的單個鏈表進行排序。例如,我有:按照姓名和出生日期對鏈接的鏈表進行排序

class Person{ 
    private String fn = "NN"; 
    private String ln = "NN"; 
    private Date dob = new Date(1, 1, 1970); 
} 

我想按姓氏,姓氏和出生日期對人員的鏈接列表進行排序。與此同時,我得到了一段代碼來適應它,但我似乎無法找到解決方法。任何幫助將不勝感激。這裏是適應以下代碼:

public void sort() { 

    TextIO.putln("sorting..."); 
    if (head == null) 
     return; 

    Node max, t, out = null, h = new Node(); 
    h.next = head; 

    while (h.next != null) { 
     // display(); 
     TextIO.putln("max=" + (max = findmax(h)).next); 
     t = max.next; 
     max.next = t.next; 
     t.next = out; 
     out = t; 
    } 
    head = out; 

} 

private Node findmax(Node h) { 
    char max = '\0'; 
    Node maxNode = h; 
    for (Node tmp = h; tmp.next != null; tmp = tmp.next) { 
     if (tmp.next.data.c >= max) { 
      max = tmp.next.data.c; 
      maxNode = tmp; 
     } 
    } 
    return maxNode; 
} 

如果沒有,詳細的建議將非常有用的謝謝。請注意,我不能使用collection.sort或任何其他ready函數,它必須實施。

感謝

回答

0

首先我想請你看看this link的。它會讓你瞭解Node類是如何實現的,以及如何實現列表。

假設你從鏈接中讀取內容,這裏有一些評論;

public void sort() { 
    //this method does ascending sort of the list 

    TextIO.putln("sorting..."); 
    if (head == null) 
     return; 

    Node max, t, out = null, h = new Node(); 
    h.next=head; //make new list node let him point to beginning of the list(head) 

    while (h.next != null) { //until we get to the end of the list 
     // display(); 

     TextIO.putln("max="+(max = findmax(h)).next); 
     //after findmax is finished we know reference 
     //to the node that contains max value 
     //and we need to bring that node to the beginning of the list 
     //that requires some reference rewiring 
     //first set t to point to next node from max 
     t = max.next; 
     //than max node will point to the next node from t 
     //this way max node becomes detached from list 
     max.next = t.next; 
     // now max node will point to some node that will represent new list head 
     // not new list just new list head 
     t.next = out; 
     out = t; 
    } 
    //after we complete sorting just point list head to the sorted list 
    head = out; 

} 

//find node that contains max value starting from some node 
private Node findmax(Node h) { 
    //declare that max is null char 
    char max = '\0'; 
    // set maxNode to be current node 
    Node maxNode = h; 
    //go through all nodes starting from current which is h 
    for (Node tmp = h; tmp.next != null; tmp = tmp.next) { 
     //if the data of some node in the list is bigger then our max value 
     if (tmp.next.data.c >= max) { 
      //then we are going to set that new value to be max 
      max = tmp.next.data.c; 
      // and set maxNode to be the node that has max value 
      maxNode = tmp; 
     } 
    } 
    return maxNode; 
} 

我的建議是查看提供的鏈接,並開始使用好的舊筆紙。這是理解列表指針和節點的最佳方式。 但是,如果你不想要紙和筆,你可以去this link,它會顯示基本列表操作的動畫。