【问题标题】:C# Linked list nested for loopsC#链表嵌套for循环
【发布时间】:2017-07-29 19:14:54
【问题描述】:

假设我在 C# 中有一个简单的链表。例如Creating a very simple linked list 其中任何一个。我想用三重嵌套的 for 循环遍历该列表。我可以展示一个包含我想要实现的数组的示例:

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
  }
 }
}

如果我有一个链表而不是数组,我该怎么做?假设我需要将所有这 3 个元素发送到一个函数。

提前感谢您的回答。

【问题讨论】:

  • 实现一个GetNthElement(LinedList, int) 方法,该方法返回传递列表的第 N 个元素。

标签: c# oop


【解决方案1】:

一般来说,您将使用 while 循环迭代您正在谈论的链表类型,例如

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 2022-01-26
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多