本文整理汇总了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();
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
}
}
示例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();
}
}
}
示例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();
}
示例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);
}
示例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)));
}
}
}
示例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;
}
示例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;
}
}
}
}
示例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<T></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);
}