C# 中的 LinkedList Contains 方法

csharpprogrammingserver side programming更新于 2025/8/11 5:22:17

这是我们的 LinkedList。

int [] num = {1, 3, 7, 15};
LinkedList<int> list = new LinkedList<int>(num);

要检查列表是否包含元素,请使用 Contains() 方法。以下示例检查列表中是否存在节点 3。

list.Contains(3)

以上代码返回 True,因为元素已找到,如下所示 −

示例

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int [] num = {1, 3, 7, 15};
      LinkedList<int> list = new LinkedList<int>(num);
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // 在末尾添加一个节点
      var newNode = list.AddLast(20);
      // 在前面添加的节点后添加一个新节点
      list.AddAfter(newNode, 30);
      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      Console.WriteLine("Is number 3 (node) in the list?: "+list.Contains(3));
   }
}

输出

1
3
7
15
LinkedList after adding new nodes...
1
3
7
15
20
30
Is number 3 (node) in the list?: True

相关文章