zoukankan      html  css  js  c++  java
  • 堆栈Stack介绍

    堆栈(Stack)代表了一个后进先出的对象集合。当您需要对各项进行后进先出的访问时,则使用堆栈。当您在列表中添加一项,称为推入元素,当您从列表中移除一项时,称为弹出元素。

    Stack 类的方法和属性

    下表列出了 Stack 类的一些常用的 属性

    属性描述
    Count 获取 Stack 中包含的元素个数。

    下表列出了 Stack 类的一些常用的 方法

    序号方法名 & 描述
    1 public virtual void Clear(); 
    从 Stack 中移除所有的元素。
    2 public virtual bool Contains( object obj ); 
    判断某个元素是否在 Stack 中。
    3 public virtual object Peek();
    返回在 Stack 的顶部的对象,但不移除它。
    4 public virtual object Pop();
    移除并返回在 Stack 的顶部的对象。
    5 public virtual void Push( object obj );
    向 Stack 的顶部添加一个对象。
    6 public virtual object[] ToArray();
    复制 Stack 到一个新的数组中。

    实例

    下面的实例演示了堆栈(Stack)的使用:

    using System;
    using System.Collections;
    
    namespace CollectionsApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                Stack st = new Stack();
    
                st.Push('A');
                st.Push('M');
                st.Push('G');
                st.Push('W');
                
                Console.WriteLine("Current stack: ");
                foreach (char c in st)
                {
                    Console.Write(c + " ");
                }
                Console.WriteLine();
                
                st.Push('V');
                st.Push('H');
                Console.WriteLine("The next poppable value in stack: {0}", 
                st.Peek());
                Console.WriteLine("Current stack: ");           
                foreach (char c in st)
                {
                   Console.Write(c + " ");
                }
                Console.WriteLine();
    
                Console.WriteLine("Removing values ");
                st.Pop();
                st.Pop();
                st.Pop();
                
                Console.WriteLine("Current stack: ");
                foreach (char c in st)
                {
                   Console.Write(c + " "); 
                }
            }
        }
    }

    当上面的代码被编译和执行时,它会产生下列结果:

    Current stack: 
    W G M A
    The next poppable value in stack: H
    Current stack: 
    H V W G M A
    Removing values
    Current stack: 
    G M A
  • 相关阅读:
    iOS中block实现的探究
    [ES6] 19. for ... of
    [ES6] 18. Map
    [ES6] 17. Set
    [ES6] 16. Object Enhancements
    [MEAN Stack] First API -- 5. Using $resource to setup REST app
    [AngularJS] Provider
    [MEAN Stack] First API -- 4. Organize app structure
    [AngularJS] ngCloak
    [Angular-Scaled Web] 9. Control your promises with $q
  • 原文地址:https://www.cnblogs.com/easypass/p/7068519.html
Copyright © 2011-2022 走看看