2014-01-29 128 views
0

對於我的編程類我必須手動進行鏈接的列表和它的一些方法,我需要插入排序的項目,這是我寫的代碼是:數組動態列表C#

 public bool Insert(Project project) 
    { 
     bool gotInserted = true; 
     if (IsInList(project) == true) 
     { 
      gotInserted = false; 
     } 
     else 
     { 
      Node tmp = this._head; 
      this._head = new Node(); 
      this._head.Project = project; 
      this._head.Next = tmp; 
      //SortList(); //is commented, because this method causes problems 
     } 
     return gotInserted; 

我可以有更好的方法來插入節點排序?

節點級:

public class Node 
{ 
    Project _project; 
    Node _next; 

    public Project Project 
    { 
     get { return _project; } 
     set { _project = value; } 
    } 

    public Node Next 
    { 
     get { return _next; } 
     set { _next = value; } 
    } 

對不起語法不好,我是奧地利人,並在我的空閒時間我通常沒有用英語思考。

+1

你的意思是你現在有一個鏈接列表。爲了讓它排序,你首先必須尋找適當的部分來插入。爲什麼不使用List <>? – RvdK

+1

我猜測,因爲這是一個類,他必須創建自己的自制版本的List <>'而不是僅僅使用現有的框架。 – ppalms

+1

如果此代碼有效,但排序會導致問題,請顯示排序代碼及其導致的問題。 – CodeCaster

回答

0

您需要從頭開始遍歷列表並檢查每個項目。當你找到一個較大的物品時,你應該在那一點插入物品,然後讓新物品指向那個舊物品。

您不想插入項目,然後嘗試對其進行排序。您需要首先找到正確的插入點。

希望這會有所幫助。

2

每次插入後排序非常無效,而是嘗試以排序的方式插入每個節點。

以排序的方式插入需要2個步驟: -

1)確定節點的位置: -

2)插入該節點。

首先找到正確的位置(使用while循環),然後將其插入相關位置。

外匯

1 - > 2 - > 5> 6是列表。

您必須在其中插入3。

1)找到相關的地方(即2)
2)創建一個新的節點
3)作出newNode的Next屬性等於)的2 Next財產
4分配的2 Next物業newNode。

0

您需要確定Project類中可以排序的字段或屬性(例如某些id),或者創建一個使用多個變量的方法,這樣您可以檢查條件並確定正確的正如Rvdk所說的那樣。

public bool Insert(Project project) 
{ 
bool gotInserted = true; 

if (IsInList(project) == true) 
{ 
    gotInserted = false; 
} 
else 
{ 
    Node tmp = this._head; 

    while(project.id < tmp.Project.id) 
    { 
     tmp = tmp.Next; 
    } 

    this._head = new Node(); 
    this._head.Project = project; 
    this._head.Next = tmp; 
} 

return gotInserted; 
}