首页  >  文章  >  后端开发  >  堆栈与 C# 示例

堆栈与 C# 示例

WBOY
WBOY转载
2023-09-20 22:45:051101浏览

堆栈与 C# 示例

C# 中的 Stack 类表示一个简单的后进先出 (LIFO) 非泛型对象集合。

以下是 Stack 类的属性 -

Sr.No 属性 &说明
1 计数 p>

获取 Stack 中包含的元素数量。

2 IsSynchronized

获取一个值,指示是否访问堆栈 同步(线程安全)。

3 SyncRoot

获取可用于同步访问的对象

以下是 Stack 类的一些方法 -

Sr.No 属性与描述 th>
1 Clear()

从堆栈中删除所有对象。

2 Clone()

创建堆栈的浅表副本。

3 Contains(Object)

 元素是否在堆栈中。

4 CopyTo(Array, Int32)

复制将 Stack 转换为现有的一维数组, 从指定的数组索引开始。

5 等于(Object)

判断指定对象是否等于 当前对象。

6 GetEnumerator() strong>

返回堆栈的 IEnumerator。

7 td> GetHashCode()

用作默认哈希函数。 (继承自Object)

8 GetType()

获取当前实例的Type。

9 Peek()

返回堆栈顶部的对象而不删除它。

10 Pop()

删除并返回位于以下位置的对象堆栈顶部

11 Push(Object )

在堆栈顶部插入一个对象。

示例

现在让我们看一些示例 -

要获取堆栈顶部的对象,代码如下 -

 现场演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Stack<string> stack = new Stack<string>();
      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<int> stack = new Stack<int>();
      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删除