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

堆栈 代表一个 后进先出 对象的集合。 堆栈 。计数属性 用于获取堆栈中包含的元素数。检索此属性的值是一个复杂的过程 O(1) 活动

null

语法:

myStack.Count 

在这里 迈斯塔克 是堆栈的名称

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

例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< string > myStack = new Stack< string >();
// 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< int > myStack = new Stack< int >();
// 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

参考:

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享