您的位置:首页 > 编程语言 > C#

C#栈的简单介绍及应用

2015-09-17 00:21 302 查看
Stack<T> 类

public class Stack<T> : IEnumerable<T>, ICollection, IEnumerable

Pop 方法弹出栈顶元素并删除

push方法压入栈顶元素

peek弹出栈顶元素不删除

ToArray 方法创建数组并将堆栈元素复制到其中

Contains 方法判断一个元素是否在栈中

在此使用MSDN中的例子。

using System;
using System.Collections.Generic;
class Example
{
public static void Main()
{
Stack<string> numbers = new Stack<string>();
numbers.Push("one");
numbers.Push("two");
numbers.Push("three");
numbers.Push("four");
numbers.Push("five");
// 遍历元素
Console.ForegroundColor = ConsoleColor.Green;
foreach (string number in numbers)
{
Console.WriteLine(number);
}
//pop弹出元素,并删除“five”
Console.WriteLine("\nPopping '{0}'", numbers.Pop());
//peek弹出元素,但不删除
Console.WriteLine("Peek at next item to destack: {0}",numbers.Peek());
//再弹出再删除
Console.WriteLine("Popping '{0}'", numbers.Pop());
// 创建新栈,复制元素
Stack<string> stack2 = new Stack<string>(numbers.ToArray());
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("\nContents of the first copy:");
foreach (string number in stack2)
{
Console.WriteLine(number);
}
// 创建双倍size数组,从一般开始存储栈元素
string[] array2 = new string[numbers.Count * 2];
numbers.CopyTo(array2, numbers.Count);
// 再创建双倍size栈,将数组再存入
Stack<string> stack3 = new Stack<string>(array2);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
foreach (string number in stack3)
{
Console.WriteLine(number);
}
//contains用法
Console.WriteLine("\nstack2.Contains(\"four\") = {0}", stack2.Contains("four"));
Console.WriteLine("\nstack2.Clear()");
//Clear()用法
stack2.Clear();
Console.WriteLine("\nstack2.Count = {0}", stack2.Count);
}
}


结果如下:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: