美文网首页
2017-9-6 stack栈 队列 字典

2017-9-6 stack栈 队列 字典

作者: 答泡浴 | 来源:发表于2017-09-06 16:47 被阅读0次

    stack 栈
    int [] numbers={1,2,3,4,5};
    string[] strs = { "li", "liu", "zhang", "wang" };
    Stack stack=new Stack(strs);
    //入栈 Push
    stack.Push(1);
    //出栈 Pop
    int number = (int)stack.Pop(); // 此时移除 wang
    object obj = stack.Pop ();
    Console.WriteLine (obj);
    //获取栈顶元素 Peek
    object obj_1=stack.Pop(); //此时移除 zhang
    Console.WriteLine (obj_1);

            object obj_2=stack.Peek();   // 输出为liu
            Console.WriteLine (obj_2);
            //是否包含某个元素
            stack.Contains("2");
            //转为数组
            object[] objs=stack.ToArray();
            //获取栈的长度
            int count=stack.Count;
            //输出栈中的每个元素
            for(int i=0;i<count;++i){
                Console.WriteLine( stack.Pop ());
            }
    

    队列
    Queue queue=new Queue(stack); //可以把栈转成队列
    Queue <int>queue_2=new Queue<int>(numbers);
    //入队列 从后面入
    queue.Enqueue("li");
    queue_2.Enqueue (1);
    //出队列
    object obj= queue.Dequeue();
    int number = queue_2.Dequeue ();
    //获取队列的头部元素
    object obj_1=queue.Peek();
    int number_1 = queue_2.Peek ();
    Console.WriteLine (obj_1);
    //队列元素个数
    queue_2.Count;
    queue.Count;
    Console.WriteLine (queue.Count);
    字典
    Dictionary<string,int>dic=new Dictionary<string, int>();

            dic.Add ("One", 1);
            dic.Add ("Two", 2);
    
            int number = dic ["One"];
            //修改
            dic ["One"]=3;
            int number1 = dic ["One"];
            Console.WriteLine (number1);
    
            Dictionary<string,string>strDic=new Dictionary<string, string>();
            //若是没有 会自动加   键是独一无二的  值是可以重复的.
            strDic ["Li"] = "an";
            strDic ["Li"] = null;
            //值就变为Null了
            Console.WriteLine (strDic["Li"]);
    
            strDic.Remove ("Li");
            //打印字典长度 (键和值 一起)单位是 对;
            Console.WriteLine (strDic.Count);
            //是否包含指定的键
            if (dic.ContainsKey ("Three")) {
                Console.WriteLine ("XXXXX");
            }
            //是否包含指定的值
            if (dic.ContainsValue (2)) {
                Console.WriteLine ("Value is 2");
            }
                                //keys 表示字典里对应的键
            foreach (string key in dic.Keys) {
                Console.WriteLine (key+" : "+dic[key]);
            }
            foreach (int value in dic.Values) {
                Console.WriteLine (value);
            }
    

    相关文章

      网友评论

          本文标题:2017-9-6 stack栈 队列 字典

          本文链接:https://www.haomeiwen.com/subject/budvjxtx.html