📜  C#|获取堆栈中包含的元素数

📅  最后修改于: 2021-05-30 01:01:03             🧑  作者: Mango

堆栈表示对象的后进先出集合。
Stack .Count属性用于获取堆栈中包含的元素数。检索此属性的值是O(1)操作。

句法:

myStack.Count 

这里myStack是Stack 的名称

返回值:该属性返回Stack 中包含的元素数。

范例1:

// C# code to Get the number of
// elements contained in the Stack
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("Chandigarh");
        myStack.Push("Delhi");
        myStack.Push("Noida");
        myStack.Push("Himachal");
        myStack.Push("Punjab");
        myStack.Push("Jammu");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
    }
}
输出:
Total number of elements in the Stack are : 6

范例2:

// C# code to Get the number of
// elements contained in the Stack
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack of Integers
        Stack myStack = new Stack();
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements in the Stack are : ");
  
        // The function should return 0
        // as the Stack is empty and it
        // doesn't contain any element
        Console.WriteLine(myStack.Count);
    }
}
输出:
Total number of elements in the Stack are : 0

参考:

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