Метод Stack.Push () в C #

Опубликовано: 7 Марта, 2022

Этот метод (входит в пространство имен System.Collections ) используется для вставки объекта в верхнюю часть стека. Если счетчик уже равен емкости, емкость стека увеличивается за счет автоматического перераспределения внутреннего массива, а существующие элементы копируются в новый массив перед добавлением нового элемента. Если Count меньше емкости стека, Push - это операция O (1). Если емкость необходимо увеличить для размещения нового элемента, Push становится операцией O (n), где n - Count.

Синтаксис:

публичный виртуальный void Push (объект obj);

Example:

// 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);
    }
}
Output:
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



C#