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


C# Stack.Push方法代码示例

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


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

示例1: Stack

        private static int Stack(string rpn)
        {
            string operators = "+-*/";
            Func<int, int, int>[] functions = new Func<int, int, int>[]
            {
                (x, y) => x + y,
                (x, y) => x - y,
                (x, y) => x * y,
                (x, y) => x / y,
            };

            string[] tokens = rpn.Split(',');
            Stack<int> values = new Stack<int>();

            foreach(string token in tokens)
            {
                int index = operators.IndexOf(token);
                if (index == -1)
                {
                    values.Push(int.Parse(token));
                    continue;
                }

                int y = values.Pop();
                int x = values.Pop();

                values.Push(functions[index](x, y));
            }

            return values.Pop();
        }
开发者ID:mmoroney,项目名称:Algorithms,代码行数:31,代码来源:EvaluateRPN.cs

示例2: GetValue

 public IItem GetValue(IDictionary<string, IItem> variables) {
   var stack = new Stack<object>();
   int i = 0;
   try {
     for (; i < tokens.Count; i++) {
       var token = tokens[i];
       double d;
       if (TryParse(token, out d)) {
         stack.Push(d);
       } else if (token.StartsWith("\"")) {
         stack.Push(GetVariableValue(variables, token.Substring(1, token.Length - 2).Replace("\\\"", "\"")));
       } else if (token.StartsWith("'")) {
         stack.Push(token.Substring(1, token.Length - 2).Replace("\\'", "'"));
       } else {
         Apply(token, stack, variables);
       }
     }
   } catch (Exception x) {
     throw new Exception(string.Format(
       "Calculation of '{1}'{0}failed at token #{2}: {3} {0}current stack is: {0}{4}", Environment.NewLine,
       Formula, i, TokenWithContext(tokens, i, 3),
       string.Join(Environment.NewLine, stack.Select(AsString))),
       x);
   }
   if (stack.Count != 1)
     throw new Exception(
       string.Format("Invalid final evaluation stack size {0} (should be 1) in formula '{1}'",
       stack.Count, Formula));
   var result = stack.Pop();
   if (result is string) return new StringValue((string)result);
   if (result is int) return new IntValue((int)result);
   if (result is double) return new DoubleValue((double)result);
   if (result is bool) return new BoolValue((bool)result);
   return null;
 }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:35,代码来源:Calculator.cs

示例3: GetFilesInProject

        /// <summary>
        /// Gets a list of all the files in the project.
        /// </summary>
        /// <returns>A list of relative <c>Uri</c> objects that reference a single file within the project's root directory.</returns>
        public List<string> GetFilesInProject()
        {
            List<string> results = new List<string>();
            Stack<string> stack = new Stack<string>();

            stack.Push(RootPath);

            while (stack.Count > 0)
            {
                string current = stack.Pop();

                foreach (string filePath in Directory.GetFiles(current))
                {
                    if (fileWatcher.Extensions.Count == 0 || fileWatcher.Extensions.Contains(Path.GetExtension(filePath)))
                    {
                        results.Add(Utility.MakeRelativePath(RootPath, filePath));
                    }
                }

                foreach (string dirPath in Directory.GetDirectories(current))
                {
                    stack.Push(dirPath);
                }
            }

            return results;
        }
开发者ID:MemoryPenguin,项目名称:CodeSync,代码行数:31,代码来源:Project.cs

示例4: Connected

        // Uses depth-first search to check if the graph induced by the subgraph given as a parameter is connected
        // In other words, we retreive all edges from the original graph and check the subgraph for connectedness
        public static bool Connected(Datastructures.Graph graph, BitSet subgraph)
        {
            // Vertices that are visited
            Set<int> visited = new Set<int>();

            // Stack of vertices yet to visit
            Stack<int> stack = new Stack<int>();

            // Initial vertex
            int s = subgraph.First();
            stack.Push(s);

            // Continue while there are vertices on the stack
            while (stack.Count > 0)
            {
                int v = stack.Pop();

                // If we have not encountered this vertex before, then we check for all neighbors if they are part of the subgraph
                // If a neighbor is part of the subgraph it means that we have to push it on the stack to explore it at a later stage
                if (!visited.Contains(v))
                {
                    visited.Add(v);

                    foreach (int w in graph.OpenNeighborhood(v))
                        if (subgraph.Contains(w))
                            stack.Push(w);
                }
            }

            // If we visited an equal number of vertices as there are vertices in the subgraph then the subgraph is connected
            return visited.Count == subgraph.Count;
        }
开发者ID:Miloan,项目名称:BooleanWidth,代码行数:34,代码来源:DepthFirstSearch.cs

示例5: GetRecursiveDependentsAsync

        ///<summary>Gets all files that indirectly depend on the specified file.</summary>
        public async Task<IEnumerable<string>> GetRecursiveDependentsAsync(string fileName)
        {
            HashSet<GraphNode> visited;
            fileName = Path.GetFullPath(fileName);
            using (await rwLock.ReadLockAsync())
            {
                GraphNode rootNode;
                if (!nodes.TryGetValue(fileName, out rootNode))
                    return Enumerable.Empty<string>();

                var stack = new Stack<GraphNode>();
                stack.Push(rootNode);
                visited = new HashSet<GraphNode> { rootNode };
                while (stack.Count > 0)
                {
                    foreach (var child in stack.Pop().Dependents)
                    {
                        if (!visited.Add(child)) continue;
                        stack.Push(child);
                    }
                }
                // Don't return the original file.
                visited.Remove(rootNode);
            }
            return visited.Select(n => n.FileName);
        }
开发者ID:kodybrown,项目名称:WebEssentials2013,代码行数:27,代码来源:DependencyGraph.cs

示例6: GetAllTypeHierarchyMembers

        protected virtual IEnumerable<IEngineConfigurationTypeMember> GetAllTypeHierarchyMembers(IEngineConfiguration baseConfiguration, IEngineConfigurationType sourceType)
        {
            Stack<IEngineConfigurationType> configurationStack = new Stack<IEngineConfigurationType>();
            Type currentType = sourceType.RegisteredType;
            IEngineConfigurationType currentTypeConfiguration = null;

            // Get all the base types into a stack, where the base-most type is at the top
            while (currentType != null)
            {
                currentTypeConfiguration = baseConfiguration.GetRegisteredType(currentType);
                if (currentTypeConfiguration != null) { configurationStack.Push(currentTypeConfiguration); }
                currentType = currentType.BaseType;
            }

            // Put all the implemented interfaces on top of that
            foreach (var interfaceType in sourceType.RegisteredType.GetInterfaces())
            {
                currentTypeConfiguration = baseConfiguration.GetRegisteredType(interfaceType);
                if (currentTypeConfiguration != null)
                {
                    configurationStack.Push(currentTypeConfiguration);
                }
            }

            var membersToApply = (from typeConfig in configurationStack
                                  from memberConfig in typeConfig.GetRegisteredMembers()
                                  select memberConfig).ToArray();

            return membersToApply;
        }
开发者ID:KCL5South,项目名称:KCLAutoPoco,代码行数:30,代码来源:CascadeBaseTypeConfigurationAction.cs

示例7: GetDirectoryFiles

        /// <summary>
        /// Given a path to a directory, scan all the .log, .txt files in the directory and subdirectories to store information in memory and work with the data
        /// </summary>
        /// <param name="directory">The path to the directory in which Kudu is storing log files. (*note same location in azure)</param>
        /// <returns>Dictionary where the key is the fullname or absolute path of the log file that we scanned and the value is the length of that file.</returns>
        public static Dictionary<string, long> GetDirectoryFiles(string directory)
        {
            //using a stack, store the directory names in the data structure, and follow a post-order traversal in traversing the log files
            Stack<string> stack = new Stack<string>();
            Dictionary<string, long> files = new Dictionary<string, long>();
            //begin by pushing the directory where the files are
            stack.Push(directory);
            string currentDirectory = null;
            while (stack.Count > 0)
            {
                //FIFO get the top directory to scan through
                currentDirectory = stack.Pop();
                string[] subDirectories;
                subDirectories = Directory.GetDirectories(currentDirectory);
                //traverse each file and add the file path to the dictionary
                foreach (string fileName in Directory.GetFiles(currentDirectory))
                {
                    //be sure that the files are what we are looking for
                    if (!MatchFilters(fileName))
                    {
                        continue;
                    }
                    files.Add(fileName, new FileInfo(fileName).Length);
                    System.Diagnostics.Trace.WriteLine(fileName);
                }

                //after adding all the files to the dictionary for the current directory, push the paths of the subdirectories to the stack and continue the loop
                foreach (string subDirectory in subDirectories)
                {
                    stack.Push(subDirectory);
                }
            }
            return files;
        }
开发者ID:projectkudu,项目名称:IISLogAnalyzerSiteExtension,代码行数:39,代码来源:LogServiceHelper.cs

示例8: Main

        public static void Main()
        {
            int n = int.Parse(Console.ReadLine().Trim());
            Stack<string> undoCollection = new Stack<string>();
            string textEditor = string.Empty;
            for (int i = 0; i < n; i++)
            {
                string[] commands =
                    Console.ReadLine()
                    .Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                    .ToArray();

                switch (commands[0])
                {
                    case "1":
                        undoCollection.Push(textEditor);
                        textEditor += commands[1];
                        break;
                    case "2":
                        undoCollection.Push(textEditor);
                        int index = textEditor.Length - int.Parse(commands[1]);
                        textEditor = textEditor.Remove(index, int.Parse(commands[1]));
                        break;
                    case "3":
                        Console.WriteLine(textEditor[int.Parse(commands[1]) - 1]);
                        break;
                    case "4":
                        textEditor = undoCollection.Peek();
                        undoCollection.Pop();
                        break;
                }
            }
        }
开发者ID:IskraNikolova,项目名称:Advanced-CSharp,代码行数:33,代码来源:SimpleTextEditor.cs

示例9: Page_PreRender

        protected void Page_PreRender( object sender, EventArgs e )
        {
            using( var dc = new DCFactory<CmsDataContext>() )
            {
                var groups = dc.DataContext.CatalogItems.GroupBy( c => c.ParentItemID ).ToDictionary( g => g.Key ?? 0 );

                if( groups.Count != 0 )
                {
                    var list = new List<object>();
                    var stack = new Stack<KeyValuePair<CatalogItem,int>>();

                    foreach( var item in groups[ 0 ].OrderByDescending( c=>c.CatalogItemPriority ) )
                        stack.Push( new KeyValuePair<CatalogItem, int>( item, 0 ) );

                    while( stack.Count != 0 )
                    {
                        var node = stack.Pop();
                        list.Add( new { CatalogItem = node.Key, Level = node.Value } );

                        if( groups.ContainsKey( node.Key.CatalogItemID ) )
                        {
                            foreach( var item in groups[ node.Key.CatalogItemID ].OrderByDescending( c => c.CatalogItemPriority ) )
                                stack.Push( new KeyValuePair<CatalogItem, int>( item, node.Value + 1 ) );
                        }
                    }

                    _repeater.DataSource = list;
                    _repeater.DataBind();
                }

            }
        }
开发者ID:dmziryanov,项目名称:ApecAuto,代码行数:32,代码来源:List.aspx.cs

示例10: 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

示例11: GetClusterAtNoRemove

 public void GetClusterAtNoRemove(int i, out int[] c1, out int[] c2)
 {
     HashSet<int> cluster1 = new HashSet<int>();
     HashSet<int> cluster2 = new HashSet<int>();
     Stack<int> todo1 = new Stack<int>();
     Stack<int> todo2 = new Stack<int>();
     todo1.Push(i);
     while (todo1.Count > 0 || todo2.Count > 0){
         if (todo1.Count > 0){
             int next = todo1.Pop();
             if (!cluster1.Contains(next)){
                 if (neighborList1.ContainsKey(next)){
                     cluster1.Add(next);
                     foreach (int x in neighborList1[next]){
                         todo2.Push(x);
                     }
                 }
             }
         } else{
             int next = todo2.Pop();
             if (!cluster2.Contains(next)){
                 if (neighborList2.ContainsKey(next)){
                     cluster2.Add(next);
                     foreach (int x in neighborList2[next]){
                         todo1.Push(x);
                     }
                 }
             }
         }
     }
     c1 = ArrayUtils.ToArray(cluster1);
     c2 = ArrayUtils.ToArray(cluster2);
 }
开发者ID:JurgenCox,项目名称:compbio-base,代码行数:33,代码来源:NeighbourListBipartite.cs

示例12: CopyDirectory

        public static void CopyDirectory(string source, string dest, bool @override = true)
        {
            //if (IsSubOf(dest, source))
            //{
            //    throw new KoobooException("Could not complete operation since target directory is under source directory.".Localize());
            //}
            var stack = new Stack<Folders>();
            stack.Push(new Folders(source, dest));

            while (stack.Count > 0)
            {
                var folders = stack.Pop();
                Directory.CreateDirectory(folders.Target);
                foreach (var file in EnumerateFilesExludeHidden(folders.Source).ToArray())
                {
                    string targetFile = Path.Combine(folders.Target, file.Name);

                    if (File.Exists(targetFile))
                    {
                        if ([email protected])
                        {
                            continue;
                        }
                        File.Delete(targetFile);
                    }
                    File.Copy(file.FullName, targetFile);
                }

                foreach (var folder in folders.SourceSubFolders)
                {
                    stack.Push(new Folders(folder.FullName, Path.Combine(folders.Target, folder.Name)));
                }
            }
        }
开发者ID:Epitomy,项目名称:CMS,代码行数:34,代码来源:IOUtility.cs

示例13: FindMatches

    // Returns a list of all fruits matching this one.
    private List<Transform> FindMatches()
    {
        var spawn = transform.parent.GetComponent<SpawnScript>();
        var grid = spawn.BuildMatcherGrid();
        var tags  = new List<string>();

        // iterate the array vertically, horizontally, and diagonally looking for matches.
        var matched = new List<Transform>();
        var matchChecks = new Stack<Transform>();
        matchChecks.Push(transform);
        while (matchChecks.Count != 0) {
            var checking = matchChecks.Pop();
            matched.Add(checking);
            var x = spawn.FindFruitColumn(checking.position.x);
            var y = spawn.FindFruitRow(checking.position.y);
            // All directions one square away from this one, including diagonally
            for (int dx = -1; dx <= 1; dx++) {
                for (int dy = -1; dy <= 1; dy++) {
                    var x2 = x + dx;
                    var y2 = y + dy;
                    if (0 <= x2 && x2 < spawn.Size.x && 0 <= y2 && y2 < spawn.Size.y) {
                        var candidate = grid[x2, y2];
                        if (candidate) {
                            tags.Add (candidate.tag);
                            if (candidate.tag == checking.tag && !matched.Contains(candidate)) {
                                // it's a new match! Check for more matches adjacent to this match.
                                matchChecks.Push(candidate);
                            }
                        }
                    }
                }
            }
        }
        return matched;
    }
开发者ID:n8twj,项目名称:fruitgame,代码行数:36,代码来源:CellScript.cs

示例14: GetCombinations

        private static IEnumerable<int[]> GetCombinations(int n, int k)
        {
            int[] result = new int[k];
            Stack<int> numbers = new Stack<int>();
            numbers.Push(1);

            while (numbers.Count > 0)
            {
                int index = numbers.Count - 1;
                int numValue = numbers.Pop();

                while (numValue <= n)
                {
                    result[index] = numValue;
                    index++;
                    numValue++;

                    numbers.Push(numValue);

                    if (index == k)
                    {
                        yield return result;
                        break;
                    }
                }
            }
        }
开发者ID:aanguelov,项目名称:AlgorithmsHomeworks,代码行数:27,代码来源:GenerateCombinationsIteratively.cs

示例15: GetFullName

        /// <summary>
        /// Returns the full name of a type, including its namespace and containing type. Generic types
        /// have their names decorated with their arity, e.g. <c>Foo`1</c> for <c>Foo&lt;T&gt;</c>.
        /// </summary>
        /// <param name="type">The type for which to get the full name.</param>
        /// <returns>The full name of the type.</returns>
        public static string GetFullName(this INamedTypeSymbol type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var nameParts = new Stack<string>();
            nameParts.Push(type.GetDecoratedName());
            var containingType = type.ContainingType;
            while (containingType != null)
            {
                nameParts.Push(containingType.GetDecoratedName());
                containingType = containingType.ContainingType;
            }

            var containingNamespace = type.ContainingNamespace;
            while (!string.IsNullOrEmpty(containingNamespace?.Name))
            {
                nameParts.Push(containingNamespace.Name);
                containingNamespace = containingNamespace.ContainingNamespace;
            }

            return string.Join(".", nameParts);
        }
开发者ID:bman61,项目名称:FakeItEasy,代码行数:31,代码来源:SymbolExtensions.cs


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