当前位置: 首页>>代码示例>>C#>>正文


C# Stack.Peek方法代码示例

本文整理汇总了C#中Stack.Peek方法的典型用法代码示例。如果您正苦于以下问题:C# Stack.Peek方法的具体用法?C# Stack.Peek怎么用?C# Stack.Peek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Stack的用法示例。


在下文中一共展示了Stack.Peek方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CalculateExpression

        private static double CalculateExpression(string expression)
        {
            var values = new Stack<double>();
            var operators = new Stack<char>();

            for (int i = 0; i < expression.Length; i++)
            {
                var token = expression[i];
                if (token == ' ')
                {
                    continue;
                }

                if ('0' <= token && token <= '9')
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(token);

                    while (i + 1 < expression.Length && (('0' <= expression[i + 1] && expression[i + 1] <= '9') || expression[i + 1] == '.'))
                    {
                        sb.Append(expression[i + 1]);
                        i++;
                    }

                    values.Push(double.Parse(sb.ToString()));
                }
                else if (token == '(')
                {
                    operators.Push(token);
                }
                else if (token == ')')
                {
                    while (operators.Peek() != '(')
                    {
                        var result = GetCalculation(operators.Pop(), values.Pop(), values.Pop());
                        values.Push(result);
                    }

                    operators.Pop();
                }
                else if (token == '+' || token == '-' || token == '*' || token == '/')
                {
                    while (operators.Count > 0 && HasPrecedence(token, operators.Peek()))
                    {
                        var result = GetCalculation(operators.Pop(), values.Pop(), values.Pop());
                        values.Push(result);
                    }

                    operators.Push(token);
                }
            }

            while (operators.Count > 0)
            {
                var result = GetCalculation(operators.Pop(), values.Pop(), values.Pop());
                values.Push(result);
            }

            return values.Pop();
        }
开发者ID:Nezhdetov,项目名称:Software-University,代码行数:60,代码来源:CalculateArithmeticExpression.cs

示例2: ToTree

        public static VisualizationNode ToTree(IEnumerable<XamlNode> xamlNodes)
        {
            var enumerator = xamlNodes.GetEnumerator();

            var stack = new Stack<VisualizationNode>();
            stack.Push(new VisualizationNode("Root"));

            while (enumerator.MoveNext())
            {
                var current = enumerator.Current;

                if (LowersLevel(current))
                {
                    stack.Pop();
                }
                else
                {
                    var item = new VisualizationNode(current);
                    stack.Peek().Children.Add(item);

                    if (RaisesLevel(current))
                    {
                        stack.Push(item);
                    }
                }
            }

            return stack.Peek();
        }
开发者ID:gitter-badger,项目名称:OmniXAML,代码行数:29,代码来源:NodeVisualizer.cs

示例3: Run

		protected override void Run ()
		{
			MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument;
			PlayScriptParser parser = new PlayScriptParser ();
			var unit = parser.Parse (doc.Editor);
			if (unit == null)
				return;
			var node = unit.GetNodeAt (doc.Editor.Caret.Line, doc.Editor.Caret.Column);
			if (node == null)
				return;
			Stack<AstNode > nodeStack = new Stack<AstNode> ();
			nodeStack.Push (node);
			if (doc.Editor.IsSomethingSelected) {
				while (node != null && doc.Editor.MainSelection.IsSelected (node.StartLocation, node.EndLocation)) {
					node = node.Parent;
					if (node != null) {
						if (nodeStack.Count > 0 && nodeStack.Peek ().StartLocation == node.StartLocation && nodeStack.Peek ().EndLocation == node.EndLocation)
							nodeStack.Pop ();
						nodeStack.Push (node);
					}
				}
			}
			
			if (nodeStack.Count > 2) {
				nodeStack.Pop (); // parent
				nodeStack.Pop (); // current node
				node = nodeStack.Pop (); // next children in which the caret is
				doc.Editor.SetSelection (node.StartLocation, node.EndLocation);
			} else {
				doc.Editor.ClearSelection ();
			}
		}
开发者ID:RainsSoft,项目名称:playscript-monodevelop,代码行数:32,代码来源:ExpandSelectionHandler.cs

示例4: top100

        public int[] top100(int[] n)
        {
            Stack<int> top100 = new Stack<int>();
            Stack<int> temp = new Stack<int>();

            for (int i = 0; i < n.Length; i++)
            {
                if (top100.Count == 100 && top100.Peek() >= n[i]) continue;

                while (top100.Count == 0 || n[top100.Peek()] < n[i])
                {
                    temp.Push(top100.Pop());
                }

                top100.Push(i);

                while (temp.Count > 1)
                {
                    top100.Push(temp.Pop());
                }

                temp.Pop();
            }

            return top100.ToArray();
        }
开发者ID:scripni,项目名称:algo,代码行数:26,代码来源:Top100Numbers.cs

示例5: LargestRectangleArea

        private int LargestRectangleArea(int[] height)
        {
            int[] answers = new int[height.Length];
            Stack<int> stack = new Stack<int>();

            for (int i = 0; i < height.Length; i++)
            {
                while (stack.Count > 0 && height[stack.Peek()] >= height[i])
                {
                    stack.Pop();
                }
                int leftEdge = stack.Count > 0 ? stack.Peek() : -1;
                answers[i] = i - leftEdge - 1;
                stack.Push(i);
            }

            int max = 0;
            stack.Clear();
            for (int i = height.Length - 1; i >= 0; i--)
            {
                while (stack.Count > 0 && height[stack.Peek()] >= height[i])
                {
                    stack.Pop();
                }
                int rightEdge = stack.Count > 0 ? stack.Peek() : height.Length;
                answers[i] += rightEdge - i - 1;
                stack.Push(i);

                int current = height[i] * (answers[i] + 1);
                max = Math.Max(current, max);
            }

            return max;
        }
开发者ID:bluesteyes,项目名称:LeetSharp,代码行数:34,代码来源:Q085_MaximalRectangle.cs

示例6: CheckBracketsInExpression

 static bool CheckBracketsInExpression(string input)
 {
     Stack<char> stack = new Stack<char>();
     bool bracketsAreCorrect = true;
     for (int i = 0; i < input.Length; i++)
     {
         char currentChar = input[i];
         if (currentChar == '(')
         {
             stack.Push(currentChar);
         }
         else if (currentChar == ')')
         {
             if (!stack.Contains('('))
             {
                 bracketsAreCorrect = false;
                 break;
             }
             while (stack.Peek() != '(')
             {
                 stack.Pop();
             }
             stack.Pop();
         }
     }
     while (stack.Count > 0)
     {
         if (stack.Peek() == '(' || stack.Peek() == ')')
         {
             bracketsAreCorrect = false;
             break;
         }
     }
     return bracketsAreCorrect;
 }
开发者ID:tdochev,项目名称:TelerikAcademy,代码行数:35,代码来源:CheckBrackets.cs

示例7: Main

        static void Main(string[] args)
        {
            Stack<String> pilha = new Stack<String>();
            //System.Collections.Stack-> de Objects

            pilha.Push("prato");
            pilha.Push("outro prato");
            pilha.Push("panela");

            foreach (var item in pilha)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(pilha.Peek());
            Console.WriteLine(pilha.Peek());
            Console.WriteLine(pilha.Peek());

            while(pilha.Count > 0)
                Console.WriteLine(pilha.Pop());

            Console.WriteLine(pilha.Count);

            Console.ReadKey();
        }
开发者ID:50minutos,项目名称:MOC-10266,代码行数:25,代码来源:Program.cs

示例8: VerifyPreorder

    public bool VerifyPreorder(int[] preorder)
    {
        if(preorder == null || preorder.Length <= 2){ return true; }

        var s = new Stack<int>();
        s.Push(preorder[0]);
        var min = int.MinValue;
        for(int i = 1; i < preorder.Length; i++){
            var curr = preorder[i];

            if(curr<=min){ return false;}

            var parent = s.Peek();

            if(curr > parent){
                while(curr > parent){
                    min = s.Pop();
                    parent = s.Any() ? s.Peek() : int.MaxValue;
                }
            }

            s.Push(curr);
        }

        return true;
    }
开发者ID:WillFr,项目名称:train,代码行数:26,代码来源:Solution+I.cs

示例9: FindNearestCommonParent

        private static int FindNearestCommonParent(int node1, int node2)
        {
            Stack<int> parentsToNode1 = new Stack<int>();
            Stack<int> parentsToNode2 = new Stack<int>();

            parentsToNode1.Push(node1);
            parentsToNode2.Push(node2);

            while (true)
            {
                if (parentsToNode2.Contains(parentsToNode1.Peek()))
                    return parentsToNode1.Peek();
                if (parentsToNode1.Contains(parentsToNode2.Peek()))
                    return parentsToNode2.Peek();
                if (node1 != treeRoot)
                {
                    node1 = parents[node1];
                    parentsToNode1.Push(node1);
                }
                if (node2 != treeRoot)
                {
                    node2 = parents[node2];
                    parentsToNode2.Push(node2);
                }
            }
        }
开发者ID:nadiahristova,项目名称:Data-Structures-Algorithms-and-Complexity,代码行数:26,代码来源:LongestPathInTree.cs

示例10: LoadTree

        private void LoadTree(EntityClassGraph entityClassGraph)
        {
            entityClassGraphTreeView.Nodes.Clear();

            if (entityClassGraph.Root == null)
                return;

            Stack<KeyValuePair<EntityMetadata, TreeNode>> baseClasses = new Stack<KeyValuePair<EntityMetadata, TreeNode>>();
            
            //Add the root node.
            TreeNode node = entityClassGraphTreeView.Nodes.Add(entityClassGraph.Root.FullName, entityClassGraph.Root.FullName, 3);
            baseClasses.Push(new KeyValuePair<EntityMetadata, TreeNode>(entityClassGraph.Root, node));

            foreach (EntityMetadata decendent in entityClassGraph.Root.Descendants)
            {
                //Find the base class that we belong to.  Since the enumeration is pre-fix order, then we can find it as 
                //an ancestor of us.
                while (!decendent.BaseClass.Equals(baseClasses.Peek().Key))
                {
                    baseClasses.Pop();
                }

                //Add this child node.
                node = baseClasses.Peek().Value.Nodes.Add(decendent.FullName, decendent.FullName, 3);
                baseClasses.Push(new KeyValuePair<EntityMetadata, TreeNode>(decendent, node));
            }
        }
开发者ID:rbramwell,项目名称:OrionSDK,代码行数:27,代码来源:EntityClassGraphForm.cs

示例11: ReorderInPostfixNotation

 /// <summary>
 /// Строит из операндов очередь в соответствии с постфиксной нотацией
 /// </summary>
 /// <param name="operands">массив операндов</param>
 /// <returns>очередь в постфиксной нотации</returns>
 public Queue<string> ReorderInPostfixNotation(IEnumerable<string> operands)
 {
     var resultQueue = new Queue<string>();
     var helperStack = new Stack<string>();
     foreach (var operand in operands)
     {
         if (IsNumber(operand))
         {
             resultQueue.Enqueue(operand);
         }
         else
         {
             if (helperStack.Count > 0)
             {
                 if (GetPriority(operand) <= GetPriority(helperStack.Peek()))
                     helperStack.Push(operand);
                 else
                 {
                     while (helperStack.Count > 0 && GetPriority(operand) > GetPriority(helperStack.Peek()))
                         resultQueue.Enqueue((helperStack.Pop()));
                     helperStack.Push(operand);
                 }
             }
             else
                 helperStack.Push(operand);
         }
     }
     foreach (var operand in helperStack)
     {
         resultQueue.Enqueue(operand);
     }
     return resultQueue;
 }
开发者ID:notin,项目名称:Calculator,代码行数:38,代码来源:PostfixCalculator.cs

示例12: BalancedDelimiter

        public bool BalancedDelimiter(String input)
        {
            Stack<char> Stacker = new Stack<char>();

            for (int i = 0; i < input.Length; i++)
            {
                if (input[i] == '(' || input[i] == '{' || input[i] == '[')
                {
                    Stacker.Push(input[i]);
                }
                else if (input[i] == ')' || input[i] == '}' || input[i] == ']')
                {
                    if (Stacker.Peek() == '(' || Stacker.Peek() == '[' || Stacker.Peek() == '{')
                    {
                        Stacker.Pop();
                    }

                }
                else
                {
                    Console.WriteLine("Char given is not Opening or closing brackets");

                }

            }

            if (Stacker.Count > 0)
                return false;
            else
                return true;
        }
开发者ID:pawanparashar,项目名称:Algorithm,代码行数:31,代码来源:Program.cs

示例13: Main

    public static void Main()
    {
        int n = int.Parse(Console.ReadLine());

        Stack<long> fib=new Stack<long>();

        fib.Push(1);
        fib.Push(1);
        for (int i = 2; i < n; i++)
        {

            long f1 = fib.Pop();
            long f2 = fib.Peek();
            fib.Push(f1);
            fib.Push(f1+f2);
            //Console.WriteLine(fib.Peek());
        }

        if (n == 0 || n == 1)
        {
            Console.WriteLine("1");
        }
        else
        {
          Console.WriteLine(fib.Peek());
        }
    }
开发者ID:AlexanderKrustev,项目名称:SoftUni,代码行数:27,代码来源:StackFinobacci.cs

示例14: Main

    static void Main()
    {
        Stack<int> myStack = new Stack<int>();
            myStack.Push(1);
            myStack.Push(2);
            myStack.Push(3);
            myStack.Push(4);
            myStack.Push(5);
            myStack.Push(6);

            int[] stackToArray = myStack.ToArray();
            Console.Write("{");
            for (int i = 0; i < stackToArray.Length-1; i++)
            {
                Console.Write(stackToArray[i] + ", ");
            }

            Console.Write(stackToArray[stackToArray.Length-1]+"}");
            Console.WriteLine();
            Console.WriteLine("the count="+myStack.Count);

            Console.WriteLine();
            Console.WriteLine(myStack.Peek());
            Console.WriteLine(myStack.Pop());
            Console.WriteLine(myStack.Peek());
            Console.WriteLine(myStack.Pop());
            Console.WriteLine(myStack.Peek());
            Console.WriteLine("the count="+myStack.Count);

            Console.WriteLine(myStack.Contains(111));

            myStack.Clear();
            Console.WriteLine("the count="+myStack.Count);
    }
开发者ID:stoyanovalexander,项目名称:TheRepositoryOfAlexanderStoyanov,代码行数:34,代码来源:ImplementStack.cs

示例15: CreatePushedExpressionUsingGroupBy

        MethodCallExpression CreatePushedExpressionUsingGroupBy(Expression pushable, Expression pushedBefore)
        {
            TreeNodeReplacer replacer = new TreeNodeReplacer();
            List<Expression> separated = Separate(pushable);
            Stack<Expression> parts = new Stack<Expression>();
            Stack<ParameterExpression> auxs = new Stack<ParameterExpression>();
            Expression replaced = pushable;
            foreach(Expression s in separated){

                parts.Push(s);
                auxs.Push(Expression.Parameter(typeof(IGrouping<,>).MakeGenericType(typeof(int), parts.Peek().Type.GetGenericArguments()[0]), makeAuxName()));

                replaced = replacer.Replace(replaced, parts.Peek(), auxs.Peek());
            }

            Expression subexpr = generateSelect(generateGroupBy(parts.Pop(), auxs.Peek().Type.GetGenericArguments()[1]),replaced,auxs.Pop());

            ParameterExpression aux = Expression.Parameter(subexpr.Type.GetGenericArguments()[0],makeAuxName());
            foreach(Expression part in parts)
            {
                subexpr = generateSelectMany(generateGroupBy(part, auxs.Peek().Type.GetGenericArguments()[1]), subexpr, auxs.Pop());
            }

            return generateSelectMany(subexpr, replacer.Replace(pushedBefore, pushable, aux), aux);
        }
开发者ID:radamus,项目名称:OptimizableLINQ,代码行数:25,代码来源:TreeModifier.cs


注:本文中的Stack.Peek方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。