zoukankan      html  css  js  c++  java
  • C#栈的简单介绍

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

    结果如图:
    
    


  • 相关阅读:
    适者生存还是强者生存
    写给十岁的清为
    毕业后的十年
    Python3 字符编码
    线段树模板
    F
    E
    D
    C
    B
  • 原文地址:https://www.cnblogs.com/zhuyuchen/p/1998036.html
Copyright © 2011-2022 走看看