📜  C#中的Stack.Push()方法

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

此方法(位于System.Collections命名空间下)用于在Stack的顶部插入一个对象。如果Count已经等于容量,则通过自动重新分配内部数组来增加Stack的容量,并在添加新元素之前将现有元素复制到新数组。如果Count小于堆栈的容量,则Push是O(1)运算。如果需要增加容量以容纳新元素,则Push变为O(n)操作,其中n为Count。

句法:

public virtual void Push (object obj);

例子:

// C# code to demonstrate the 
// Stack.Push() Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("one");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements "+
                           "in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("two");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("three");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("four");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("five");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("six");
  
        // 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 : 1
Total number of elements in the Stack are : 2
Total number of elements in the Stack are : 3
Total number of elements in the Stack are : 4
Total number of elements in the Stack are : 5
Total number of elements in the Stack are : 6

参考:

  • https://docs.microsoft.com/ena-us/dotnet/api/system.collections.stack.push?view=netframework-4.7.2