📌  相关文章
📜  C#|检查堆栈是否包含元素

📅  最后修改于: 2021-05-29 17:46:53             🧑  作者: Mango

堆栈表示对象的后进先出集合。
Stack .Contains(Object)方法用于检查元素是否在Stack 中。

句法:

public virtual bool Contains(object obj);

返回值:如果元素存在于Stack 中,则函数返回True;如果元素不存在于Stack中,则函数返回False

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to Check if a Stack
// contains an element
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack of strings
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("Geeks");
        myStack.Push("Geeks Classes");
        myStack.Push("Noida");
        myStack.Push("Data Structures");
        myStack.Push("GeeksforGeeks");
  
        // Checking whether the element is
        // present in the Stack or not
        // The function returns True if the
        // element is present in the Stack, else
        // returns False
        Console.WriteLine(myStack.Contains("GeeksforGeeks"));
    }
}
输出:
True

范例2:

// C# code to Check if a Stack
// contains an element
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack of Integers
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push(5);
        myStack.Push(10);
        myStack.Push(15);
        myStack.Push(20);
        myStack.Push(25);
  
        // Checking whether the element is
        // present in the Stack or not
        // The function returns True if the
        // element is present in the Stack, else
        // returns False
        Console.WriteLine(myStack.Contains(7));
    }
}
输出:
False

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.contains?view=netframework-4.7.2