VB.Net Stack類

2019-10-16 23:01:27

Stack類表示物件的後進先出集合。當需要對專案進行後進先出存取時使用它。當在列表中新增一個專案時稱為推播專案,當刪除它時稱為彈出專案。

Stack類的屬性和方法

下表列出了Stack類的一些常用屬性:

編號 屬性 描述
1 Count 獲取堆疊中包含的元素的數量。

下表列出了Stack類的一些常用方法:

編號 方法 描述
1 Public Overridable Sub Clear 刪除堆疊中的所有元素。
2 Public Overridable Function Contains (obj As Object) As Boolean 確定元素是否在堆疊中。
3 Public Overridable Function Peek As Object 返回堆疊頂部的物件而不刪除它。
4 Public Overridable Function Pop As Object 刪除並返回堆疊頂部的物件。
5 Public Overridable Sub Push (obj As Object) 在堆疊頂部插入一個物件。
6 Public Overridable Function ToArray As Object() 將堆疊複製到新陣列。

範例

以下範例演示如何使用堆疊:

Imports System.Collections
Module MyStack
   Sub Main()
      Dim st As Stack = New Stack()
      st.Push("A")
      st.Push("M")
      st.Push("G")
      st.Push("W")
      Console.WriteLine("Current stack: ")
      Dim c As Char
      For Each c In st
          Console.Write(c + " ")
      Next c
      Console.WriteLine()
      st.Push("V")
      st.Push("H")
      Console.WriteLine("The next poppable value in stack: {0}", st.Peek())
      Console.WriteLine("Current stack: ")
      For Each c In st
          Console.Write(c + " ")
      Next c
      Console.WriteLine()
      Console.WriteLine("Removing values ")
      st.Pop()
      st.Pop()
      st.Pop()
      Console.WriteLine("Current stack: ")
      For Each c In st
          Console.Write(c + " ")
      Next c
      Console.ReadKey()
   End Sub
End Module

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\collection>vbc MyStack.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to Visual Basic 2012, which is no longer the latest version. For compilers that support newer versions of the Visual Basic programming language, see http://go.microsoft.com/fwlink/?LinkID=533241


F:\worksp\vb.net\collection>MyStack.exe
Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A