2012-03-26 104 views
0

iam應該顯示一個txt文件中的客戶記錄,然後按照升序重新顯示它們。我有第一部分,但沒有弄清楚排序問題。方法public void添加(客戶newNode,詮釋虛擬)排序實施的鏈接列表

public void add(Customer newNode, int dummy) 

    { 
    if (head == null) // The first node 
    { 
    head = tail = this; 
    head.setData(newNode); size=1; 
    return; 
    } //************need to figure this out 
    CustomerList t = new CustomerList(); 
    head.setNext(temp); 
     getHead().getNext(); 
     head = temp; 

     //this is the part am trying to figure out 

    ++size; 
    } // add 
// Append the new node to the end of list 
public void add(Customer newNode) 
    { 
    if (head == null) // The first node 
     { 
     head = tail = this; 
     head.setData(newNode); 
     size=1; 
     return; 
     } 
    CustomerList temp = new CustomerList(newNode); 
    tail.setNext(temp); 
    getHead().getNext(); 
    tail = temp; 
    ++size; 
    } // add 

// retrieve a specific node by index 
// The index starts with 0 
public Customer get(int which) 
    { 
    if (which > size-1) 
     return null; 
    if (size < 0) 
     return null; 
    CustomerList temp = head; 
    for (int k=0; k < size; ++k) 
     { 
     if (which == k) 
      break; 
     temp = temp.getNext(); 
     } 
    return temp.getData(); 
    } // get 
+1

是否允許使用「標準java」類似於集合和算法的東西,還是您希望自己完成所有工作? – John3136 2012-03-26 04:57:04

回答

1

使用Collections.sort(您列表)以獲取列表的排序順序。

然後顯示它們獲得迭代器使用iterator()方法。

然後使用下一個()方法

+0

我猜他/她必須在不使用'Collection.sort()'的情況下對它進行排序,因爲它有可怕的作業標記。 – 2012-03-26 05:01:03

+0

我不允許使用Collection.sort()我曾試過,並被告知要重做它。 – Angel918 2012-03-26 05:08:23

+0

@ Angel918你可以說你想對哪個字段排序記錄。我的意思是使用客戶ID或名稱對他們進行排序? – 2012-03-26 05:13:20

1

啓動與實施一些方法,你將需要遍歷元素:

public void remove(Customer customer); 

public void insert(Customer customer, index); 

public void swap(int index1, int index2); 

與所有的算法,你必須採取一個元件該列表和插入它在列表中的其他位置或者簡單地交換到列表中的元素。

+0

非常感謝讓我試試。我想我已經實現了public void insert() – Angel918 2012-03-26 05:13:45

0

爲Customer類創建比較器,或者可以爲Customer類實現可比較的接口。然後使用一個排序如下策略:

  1. 如果您已經創建比較適合您的客戶,然後使用Collections.sort(您的列表,你的比較)
  2. 如果實現比較的接口,然後用Collections.sort(您的列表)

然後爲了顯示目的使用iterator()方法。你可以通過next()方法迭代列表的下一個元素。