Stack()构造函数用于初始化Stack类的新实例,该实例将为空并具有默认的初始容量。堆栈表示对象的后进先出集合。当您需要对项目进行后进先出访问时,可以使用它。在列表中添加项目时,称为推送项目,而在删除项目时,则称为弹出项目。此类位于System.Collections
命名空间下。
句法:
public Stack ();
重要事项:
- 堆栈可以容纳的元素数量称为堆栈的容量。如果将元素添加到堆栈中,则将通过重新分配内部数组来自动增加容量。
- 如果可以估计集合的大小,则指定初始容量将消除在将元素添加到堆栈中时执行许多调整大小操作的需求。
- 此构造函数是O(1)操作。
范例1:
// C# Program to illustrate how
// to create a Stack
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// st is the Stack object
// Stack() is the constructor
// used to initializes a new
// instance of the Stack class
Stack st = new Stack();
// Count property is used to get the
// number of elements in Stack
// It will give 0 as no elements
// are present currently
Console.WriteLine(st.Count);
}
}
输出:
0
范例2:
// C# Program to illustrate how
// to create a Stack
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// st is the Stack object
// Stack() is the constructor
// used to initializes a new
// instance of the Stack class
Stack st = new Stack();
Console.Write("Before Push Method: ");
// Count property is used to get the
// number of elements in Stack
// It will give 0 as no elements
// are present currently
Console.WriteLine(st.Count);
// Inserting the elements
// into the Stack
st.Push("Chandigarh");
st.Push("Delhi");
st.Push("Noida");
st.Push("Himachal");
st.Push("Punjab");
st.Push("Jammu");
Console.Write("After Push Method: ");
// Count property is used to get the
// number of elements in st
Console.WriteLine(st.Count);
}
}
输出:
Before Push Method: 0
After Push Method: 6
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.-ctor?view=netframework-4.7.2#System_Collections_Stack__ctor