颠倒链表的顺序

时间:2012-10-17 09:05:49

标签: c# asp.net

我有一个链表,它添加一个像树一样的对象,以下是打印输出 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相同的结果,有没有方法对链表的特定节点进行排序?

2 个答案:

答案 0 :(得分:2)

没有。链接列表不具有除创建项目的顺序之外的排序顺序的概念。它意味着快速遍历和添加许多项目。我不确定这个数据结构是否适合您的需求。

我不确定您的要求是什么。也许如果你能列出要求我们可以提出一些建议。

答案 1 :(得分:0)

根据您所描述的树结构看起来更合适。

关于树遍历。这是关于你是从左到右还是从右到左遍历孩子:

课程计划 {     static void Main(string [] args)     {         Node rootNode = new Node();         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