hkguile
hkguile

Reputation: 4359

reverse the order of the linked list

i have a linkedlist, which add an object like a tree, the following is the printout LinkedList nodeList = new LinkedList();

(result 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

(result B)The following should be the right order

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

So, i want to reverse the order of sub-node of Audit Committee of (ResultA) output the result of same as the ResultB, is there any method to sort the specific node of linked list?

Upvotes: 0

Views: 193

Answers (2)

coder_bro
coder_bro

Reputation: 10773

From what you are describing a Tree structure looks more suitable.

It is about tree traversal. It is about whether you traverse the children from left to right or from right to left:

class Program { static void Main(string[] args) { Node rootNode = new Node(); rootNode.Name = "root"; Node 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]);
    }
}     

}

Output:

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

Upvotes: 0

uriDium
uriDium

Reputation: 13420

No. The linked list has not concept of a sort order other than the order that the items were created. It's meant to be fast for traversing and adding many items. I am not sure that this data structure suits your needs at all.

I am not sure what your requirements are. Maybe if you could list the requirements we could make some suggestions.

Upvotes: 2

Related Questions