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

📅  最后修改于: 2021-05-29 16:43:56             🧑  作者: Mango

此方法(位于System.Collections命名空间下)用于删除并返回堆栈顶部的对象。此方法与Peek方法相似,但是Peek不会修改堆栈。

句法:

public virtual object Pop ();

返回值:返回从堆栈顶部删除的对象。

异常:如果堆栈为空,则此方法将提供InvalidOperationException。

下面的程序说明了上述方法的用法:

范例1:

// C# Program to illustrate the 
// use of Stack.Pop() Method
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("Geeks");
        myStack.Push("Geeks Classes");
        myStack.Push("Noida");
        myStack.Push("Data Structures");
        myStack.Push("GeeksforGeeks");
  
        Console.WriteLine("Number of elements in the Stack: {0}",
                                                 myStack.Count);
  
        // Retrieveing top element of Stack
        Console.Write("Top element of Stack is: ");
        Console.Write(myStack.Pop());
  
        // printing the no of Stack element
        // after Pop operation
        Console.WriteLine("\nNumber of elements in the Stack: {0}",
                                                    myStack.Count);
    }
}
输出:
Number of elements in the Stack: 5
Top element of Stack is: GeeksforGeeks
Number of elements in the Stack: 4

范例2:

// C# Program to illustrate the 
// use of Stack.Pop() Method
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push(7);
        myStack.Push(9);
  
        Console.WriteLine("Number of elements in the Stack: {0}",
                                                 myStack.Count);
  
        // Retrieveing top element of Stack
        Console.Write("Top element of Stack is: ");
        Console.Write(myStack.Pop());
  
        // printing the no of Stack element
        // after Pop operation
        Console.WriteLine("\nNumber of elements in the Stack: {0}",
                                                    myStack.Count);
    }
}
输出:
Number of elements in the Stack: 2
Top element of Stack is: 9
Number of elements in the Stack: 1

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.pop?view=netframework-4.7.2