堆疊與 C# 範例

WBOY
發布: 2023-09-20 22:45:05
轉載
1001 人瀏覽過

堆栈与 C# 示例

C# 中的 Stack 類別表示一個簡單的後進先出 (LIFO) 非泛型物件集合。

以下是Stack 類別的屬性-

Sr.No屬性&說明
1計數 p>

取得Stack 中包含的元素數。

2IsSynchronized

取得一個值,指示是否存取堆疊 同步(線程安全)。

3SyncRoot

取得可用於同步存取的對象

以下是Stack 類別的一些方法-

##Sr.No屬性與描述12Clone()3Contains(Object)4CopyTo(Array, Int32)5等於(Object)6GetEnumerator()78#GetType() ## 取得目前實例的Type 。 傳回堆疊頂端的物件而不刪除它。 刪除並傳回位於下列位置的物件堆疊頂部在堆疊頂端插入一個物件。
th>
#Clear()##從堆疊中刪除所有對象。

建立堆疊的淺表副本。

 元素是否在堆疊中。

#複製將Stack 轉換為現有的一維數組, 從指定的數組索引開始。

判斷指定物件是否等於 當前對象。

strong>傳回堆疊的 IEnumerator。

td>GetHashCode()用作預設雜湊函數。 (繼承自Object)

##8

#GetType()

9

Peek()

10

Pop()

11

Push(Object )

範例

現在讓我們來看一些範例-

要取得堆疊頂端的對象,程式碼如下-

 現場示範

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push("A");
      stack.Push("B");
      stack.Push("C");
      stack.Push("D");
      stack.Push("E");
      stack.Push("F");
      stack.Push("G");
      stack.Push("H");
      stack.Push("I");
      stack.Push("J");
      Console.WriteLine("Count of elements = "+stack.Count);
      Console.WriteLine("Element at the top of stack = " + stack.Peek());
   }
}
登入後複製

輸出

這將產生下列輸出-

Count of elements = 10
Element at the top of stack = J
Count of elements = 10
登入後複製

要檢查Stack 是否有元素,請使用C# Contains() 方法。以下是程式碼 -

範例

即時示範

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push(100);
      stack.Push(150);
      stack.Push(175);
      stack.Push(200);
      stack.Push(225);
      stack.Push(250);
      stack.Push(300);
      stack.Push(400);
      stack.Push(450);
      stack.Push(500);
      Console.WriteLine("Elements in the Stack:");      
      foreach(var val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements in the Stack = "+stack.Count);
      Console.WriteLine("Does Stack has the element 400?= "+stack.Contains(400));
   }
}
登入後複製

輸出

###這將產生以下輸出 -###
Elements in the Stack:
500
450
400
300
250
225
200
175
150
100
Count of elements in the Stack = 10
Does Stack has the element40400?= False
登入後複製
###

以上是堆疊與 C# 範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!