C#栈的简单介绍

    栈(Stack)代表了一个只有一个出口的后进先出的对象集合。在列表中添加一项,称为推入元素,从列表中移除一项时,称为弹出元素。

    Stack<T> 类

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

  • 属性

    Count  获取 Stack 中包含的元素个数

  • 方法

    Pop   移除并返回在 Stack 的顶部的对象

    push  向 Stack 的顶部添加一个对象

    peek  返回在 Stack 的顶部的对象,但不移除它

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

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

    Clear  从 Stack 中移除所有的元素。

  • 实例

在此使用MSDN中例子。以下代码及结果显示图片来自:C#栈的简单介绍及应用

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

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值