J. Brown
J. Brown

Reputation: 11

C# Linked list nested for loops

Let's say I have a simple linked list in C#. For example Creating a very simple linked list any of these. And I want to iterate through that list with triple nested for loop. I can show an example with array of what I want to achieve:

int[] a = new int[10];
//some code to place elements into that array
for(int i = 0; i<a.length; i++){
 for(int q = i; q<a.length; q++){
  for(int z = q; z<a.length; z++){
    //do stuff with a[i], a[q], a[z], for example send them to a function
  }
 }
}

How would could I do that if I had a linked list instead of an array? Let's say I need to send all these 3 elements to a function.

Thank you for your answers in advance.

Upvotes: 0

Views: 1030

Answers (1)

Dan Field
Dan Field

Reputation: 21641

Generally speaking, you're going to iterate the type of linked list you're talking about with a while loop, e.g.

LinkedList a = new LinkedList();
//some code to place elements into that array
var node = a.Head;
while(node != null)
{
   var nodeQ = node;
   while (nodeQ != null)
   {
       var nodeZ = nodeQ;
       while (nodeZ != null)
       {
           // do stuff with node, nodeQ, nodeZ
          nodeZ = nodeZ.Next;
       }
       nodeQ = nodeQ.Next;
   }
   node = node.Next;
}

Upvotes: 1

Related Questions