2012-10-17 101 views
0

我有一個鏈接列表,其中添加一個對象就像一棵樹,下面是打印輸出 LinkedList nodeList = new LinkedList();顛倒鏈接列表的順序

(結果A)

1 : Tester Meeting 
2 : Adminstrative & Operational 
3 : Functional Committees 
4 : Aduit Committee 
9 : Supporting Services Development 
8 : Medical Services Development 
7 : Information Technology Services 
6 : Human Resources Committee 
15 :   test2-2 
14 :  test2 
13 :   test1-1 
12 :  test1 
5 : Finance Committee 
10 : Regional Advisory Committees 
11 : Board Workshop 

(結果B)下面列出的是正確的順序

Tester Meeting 
Adminstrative & Operational 
Functional Committees 
Aduit Committee 
    Finance Committee 
     test1 
     test1-1 
     test2 
     test2-2 
    Human Resources Committee 
    Information Technology Services 
    Medical Services Development 
    Supporting Services Development 
Regional Advisory Committees 
Board Workshop 

所以,我要扭轉的審計委員會的子節點的順序( ResultA)輸出與ResultB相同的結果,是否有任何方法來排序鏈表的特定節點?

+1

LinkedList不是的一棵樹,所以 '子節點' 是如何實現的? –

+0

這不是排序樹的問題,而是你如何走樹。 –

+0

LinkedList排序不好,任何你不使用List <>的原因? –

回答

2

否。鏈接列表沒有排序順序的概念,而不是創建項目的順序。它意味着快速遍歷和添加許多項目。我不確定這個數據結構是否適合您的需求。

我不確定你的要求是什麼。也許如果你能列出要求,我們可以提出一些建議。

+0

存在未知數的嵌套節點,請問有沒有其他數據結構適合? – hkguile

+0

樹將能夠支持。只要確保你沒有找到任何平衡的樹。這些樹會自動調整自己以確保樹中的任何等級與樹的高度之差都不會超過1.這是爲了表現。所以你需要一棵樹來保存它的結構。 – uriDium

0

從你所描述的樹結構看起來更合適。

這是關於樹遍歷。這是關於你是否穿越孩子從左至右或從右至左:

類節目 { 靜態無效的主要(字串[] args){ 節點 =根節點新節點(); rootNode.Name =「root」; 節點node1 = new Node(); node1.Name =「child 1」;

Node node2 = new Node(); 
    node2.Name = "child 2"; 

    rootNode.Children.Add(node1); 
    rootNode.Children.Add(node2); 

    Node node3 = new Node(); 
    node3.Name = "child 3"; 



    node1.Children.Add(node3); 


    Traverse(rootNode); 

    Console.WriteLine("Reverse: "); 

    TraverseReverse(rootNode); 

} 

private static void Traverse(Node node) 
{ 
    Console.WriteLine(node.Name); 
    for (int index = 0; index < node.Children.Count;index++) 
    { 
     Traverse(node.Children[index]); 
    }    
} 

private static void TraverseReverse(Node node) 
{ 
    Console.WriteLine(node.Name); 
    for (int index = node.Children.Count-1; index >=0; index--) 
    { 
     TraverseReverse(node.Children[index]); 
    } 
}  

}

輸出:

root 
child 1 
child 3 
child 2 
Reverse: 
root 
child 2 
child 1 
child 3