当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# Stack.Push()用法及代码示例


此方法(位于System.Collections命名空间下)用于在Stack的顶部插入一个对象。如果Count已经等于容量,则通过自动重新分配内部数组来增加堆栈的容量,并在添加新元素之前将现有元素复制到新数组。如果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

参考:



相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 Stack.Push() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。