2015-05-16 45 views
0

所以我有一個名爲List的類和一個名爲SortedList的類繼承了List類。還有一個叫做節點的類。我創建了另一個包含打印方法的類。如何實現排序列表

但是,每次我插入三個名稱,例如,我打印的方法它只打印我插入的姓氏。所以我的問題是:這段代碼是否構成一個排序列表?如果是這樣,爲什麼只打印最後一個名字?

List類:

public class List { 

    protected Node head; 
    protected int length; 

    public void list() 
    { 
     head=null; 
     length=0; 
    } 
    public boolean isEmpty() 
    { 
     return head==null; 
    } 
    public Node insert(Item a) 
    { 
     length++; 
     head=new Node(a, head); 
     return head; 
    } 

sortlist一類:

public class SortList extends List { 

    private Node head; 
    public SortList() 
    { 
     this.head=null; 
    } 
    public Node getFirst() 
    { 
     return head; 
    } 
    public Node Insert(Item newitem) 
    { 
     Node node = new Node(newitem); 
     Node previous = null; 
     Node current = head; 
     while(current!=null && current.getValue().less(newitem)) 
     { 
      previous=current; 
      current=current.getNext(); 
     } 
     if(previous==null) 
     { 
      head=node; 
     } 
     else 
     { 
      previous.setNext(node); 
      node.setNext(current); 
     } 
     return head; 
    } 
    public void printlist() 
{ 

    Node current = head; //ΑΡΧΗ ΤΗΣ ΛΙΣΤΑΣ. 
    while(current!=null) 
    { 
     current.print(); 
     current = current.getNext(); 
    } 
} 

Node類:

public class Node { 

    private Item info; 
    private Node next; 
    public Node(Item dat) 
    { 
     info=dat; 
    } 
    public Node (Item dat, Node b) 
    { 
     info=dat; 
     next=b; 
    } 
    public Item getValue() 
    { 
     return info; 
    } 
    public void setNext(Node a) 
    { 
     next=a; 
    } 
    public Node getNext() 
    { 
     return next; 
    } 
    public void print() 
    { 
     info.print(); 
    } 
} 
+0

我照你問。 – Maria

+0

@ᴳᵁᴵᴰᴼ你......必須......用...... Python ......!不... JAVA! – Zizouz212

+0

爲什麼不能在列表內容的每個變化上使用'Collections.sort()'? –

回答

3

在你的List實現,你在insert()方法的一個主要缺陷:

public Node insert(Item a) 
{ 
    length++; 
    head=new Node(a, head); 
    return head; 
} 

您不會將新元素附加到列表的末尾,而是每次都替換列表的頭部,從而丟棄前一個元素。

這將解釋爲什麼你總是隻看到你插入的最後一個元素。

編輯:原來,insert()方法確實有效,因爲您將引用設置爲節點構造函數中的下一個節點。

在你的排序列表但是,您有一個針對下一個節點沒有設置一個插入的情況:

if(previous==null) 
{ 
    head=node; 

} 

我你的排序列表,您沒有設置下一個元素在節點的構造。在所有其他情況下,您將在insert()方法中設置下一個元素,但在這種情況下不會。如果要插入的元素是列表中最小的元素,則previous爲null,這是正確的 - 您的新元素是列表的新head。但是,由於您沒有設置新元素的後繼,所以列表中的所有元素現在都消失了。

如果您插入列表中的最後一個元素最小,最後一個元素也將是唯一剩下的元素,並且只打印出最後一個元素。

嘗試設置的繼任者:

if(previous==null) 
{ 
    head=node; 
    head.setNext(current); 
} 
+0

mmh,頭也許應該改名尾巴...但它應該仍然工作,因爲參考沒有丟棄,當前頭參考將是下一個新的頭 –

+0

好吧,我明白你說什麼,但你能更具體?你能給我一個例子或正確的代碼嗎? – Maria

+0

@ᴳᵁᴵᴰᴼ其實是對的,你的代碼應該可以工作。我錯過了對下一個元素的引用是在新Node的構造函數中設置的。我的錯! – Timo