代码改变世界

C#栈的简单介绍及应用

2011-04-01 14:02  闫妍  阅读(9472)  评论(0编辑  收藏  举报

堆 栈 队列都是一种一堆儿的概念。队列有两个口先进先出,栈有一个口先进后出,堆我们可以想象一下煤堆。

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);
    }
}

结果如下:

image