public bool findAncestors(int search_item, CSharp.Stack.Stack <int> ancestry) { if (search_item == this.item) { ancestry.push(this.item); return(true); } else { if (this.left_child != null && this.left_child.findAncestors(search_item, ancestry)) { ancestry.push(this.item); return(true); } else if (this.right_child != null && this.right_child.findAncestors(search_item, ancestry)) { ancestry.push(this.item); return(true); } else { return(false); } } }
public int getDistanceBetweenNodes(int node_1_item, int node_2_item) { CSharp.Stack.Stack <int> node_1_ancestry = new CSharp.Stack.Stack <int>(1000); this.root.findAncestors(node_1_item, node_1_ancestry); CSharp.Stack.Stack <int> node_2_ancestry = new CSharp.Stack.Stack <int>(1000); this.root.findAncestors(node_2_item, node_2_ancestry); int min_distance = 0; while (true) { if (!node_1_ancestry.isEmpty() && !node_2_ancestry.isEmpty()) { if (node_1_ancestry.pop() != node_2_ancestry.pop()) { min_distance += 2; } } else if (!node_1_ancestry.isEmpty()) { node_1_ancestry.pop(); min_distance++; } else if (!node_2_ancestry.isEmpty()) { node_2_ancestry.pop(); min_distance++; } else { break; } } return(min_distance); }
public static string reverseWordsInString(string str) { string result_str = ""; CSharp.Stack.Stack <char> stack = new CSharp.Stack.Stack <char>(1000); for (int i = 0; i < str.Length; i++) { char letter = str[i]; if (letter != ' ') { stack.push(letter); } if (letter == ' ' || i == str.Length - 1) { while (!stack.isEmpty()) { result_str += stack.pop(); } if (letter == ' ') { result_str += ' '; } } } return(result_str); }
public static bool isExpressionBalanced(string expression) { CSharp.Stack.Stack <char> stack = new CSharp.Stack.Stack <char>(1000); Dictionary <char, char> mapping = new Dictionary <char, char>(); mapping.Add('{', '}'); mapping.Add('[', ']'); mapping.Add('(', ')'); foreach (char letter in expression) { if (letter == '{' || letter == '(' || letter == '[') { stack.push(letter); } else if (letter == '}' || letter == ')' || letter == ']') { char last_keyword = stack.pop(); if (mapping[last_keyword] != letter) { return(false); } } } return(stack.isEmpty()); }
static void testStack() { CSharp.Stack.Stack <int> stack = new CSharp.Stack.Stack <int>(4); int[] insert_items = { 3, 6, 8, 2 }; foreach (int item in insert_items) { stack.push(item); } Console.WriteLine("peek: " + stack.peek()); Console.WriteLine("pop: " + stack.pop()); Console.WriteLine("peek: " + stack.peek()); }