2011-11-18 26 views
0

對於一個賦值,我們被要求在Java中以Bags的形式實現LinkedLists的有序和無序版本。有序版本將在覆蓋插入方法的同時簡單地擴展無序實現。有序插入與基元類型和字符串零星地工作

插入函數的排序工作...有點。給定一個測試陣列的

String[] testArray= {"z","g","x","v","y","t","s","r","w","q"}; 

輸出是

q w r s t y v x g z 

當它應該是

g q r s t v w x y z 

然而,當元件被不值混合起來的排序工作正常。例如,我最初使用上面的testArray[],而且字母顛倒了,順序完全按照它的樣子。

我的附加功能是

@Override 
public void add(E e){ 
    Iter iter= new Iter(head.prev); 
    int compValue; 
    E currentItem= null; 

    //empty list, add at first position 
    if (size < 1) 
     iter.add(e); 

    else { 

     while (iter.hasNext()){ 
      currentItem= iter.next(); //gets next item 

      //saves on multiple compareTo calls 
      compValue= e.compareTo(currentItem); 

      //adds at given location 
      if (compValue <= 0) 
       iter.add(e, iter.index); 

      else //moves on 
       currentItem= iter.next(); 
     } 
    } 
} 

迭代器功能爲

//decided to use iterator to simplify method functionality 
protected class Iter implements Iterator<E>, ListIterator<E>{ 
    protected int index= 0; 
    protected Node current= null; 

//Sets a new iterator to the index point provided 
    public Iter(int index){ 
     current= head.next; 
     this.index=0; 
     while (index > nextIndex()) //moves on to the index point 
      next(); 
    } 

public void add(E e, int index){ 
     size++; 

     Iter iterator= new Iter(index); 

     Node node= new Node(); 
     Node current= iterator.current.prev; 

     node.next= current.next; 
     node.prev= current; 
     node.next.prev= node; 
     node.prev.next= node; 

     node.item= e; 
    } 

實現。如它是現在,正在使用的唯一的東西是基本類型。我知道對象,必須編寫一個特定的可比較的類,但在這種情況下,String包含一個應該給出正確排序的compareTo()方法。

偶然的情況下,我的同學有一個類似的實現,並返回相同的結果。

使用自然排序,我該如何解決這個問題?

你的add()函數

回答

1

三件事我跳出:

  1. 應該儘快退出循環,因爲它插入新的價值;這可能並不是一個問題,但它仍然是一個效率低下的問題
  2. 您可以在循環的頂部調用next_item,但在未添加該值時再次調用它
  3. 如果您的列表只有1個值它,並且您嘗試添加一個大於列表中當前值的值,是否不會添加新值?