private static void RunStackTest() { Console.WriteLine("Start"); Console.WriteLine("Push 1"); var stack = new Stack(1); Console.WriteLine("Push 2"); stack.Push(2); Console.WriteLine("Push 3"); stack.Push(3); Console.WriteLine("Push 4"); stack.Push(4); Console.WriteLine("Pop " + stack.Pop()); Console.WriteLine("Pop " + stack.Pop()); Console.WriteLine("Pop " + stack.Pop()); Console.WriteLine("Pop " + stack.Pop()); Console.WriteLine("Pop ??????? expected Exception"); try { stack.Pop(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Push 5 on Empty stack"); stack.Push(5); Console.WriteLine("Pop " + stack.Pop()); }
//DFS public static bool ExistsPath(Graph<int> graph, int start, int destination) { var nodes = graph.Nodes; foreach (var node in nodes) { node.NodeState=State.Unvisted; } var discovered = new Stack<Node<int>>(); var currentNode = graph.FindNode(start); currentNode.NodeState = State.Visited; discovered.Push(currentNode); while (discovered.Count>0) { currentNode = discovered.Pop(); foreach (var node in currentNode.Neighbors) { if (node.NodeState.Equals(State.Unvisted)) { node.NodeState=State.Visited; discovered.Push(node); } } } return graph.FindNode(destination).NodeState.Equals(State.Visited); }
public void MinStack_Count_Equals_Stack_Count_For_One_Million_Items() { DataStructures.Stack stack = new DataStructures.Stack(); for (int i = 0; i < 1000000; i++) { stack.Push(i); } Assert.AreEqual(1000000, stack.GetMinStackCount()); }
public void Adding_Items_In_Descending_Order_Sets_Minimum_To_Last_Value() { DataStructures.Stack stack = new DataStructures.Stack(); stack.Push(5); stack.Push(4); stack.Push(3); stack.Push(2); stack.Push(1); Assert.AreEqual(1, stack.GetMinimumItem()); }
public void Adding_Items_In_Descending_Order_Then_Popping_Sets_Minimum_To_Previous_Minimum_Value() { DataStructures.Stack stack = new DataStructures.Stack(); stack.Push(5); stack.Push(4); stack.Push(3); stack.Push(2); stack.Push(1); stack.Pop(); Assert.AreEqual(2, stack.GetMinimumItem()); }
public void GetMinimum_Runs_In_Constant_Time_For_One_Million_Items() { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); DataStructures.Stack stack = new DataStructures.Stack(); for (int i = 0; i <= 1000000; i++) { stack.Push(i); } watch.Start(); int result = stack.GetMinimumItem(); watch.Stop(); Assert.AreEqual(0, watch.ElapsedMilliseconds); }
//--------------------------------------------------------------------- //------------- D F S + I T E R A T I V E ------------------- //--------------------------------------------------------------------- //DFS: 先序 Pre-order Traversal, Stack public List<int> PreOrderTraversal_Iterative1(TreeNode root) { List<int> result = new List<int>(); Stack<TreeNode> stack = new Stack<TreeNode>(); stack.Push(root); while (stack.Count != 0) { root = stack.Pop(); if (root != null) { result.Add(root.val); //Prevent pushing null node to enhance performance. if (root.right != null) stack.Push(root.right); if (root.left != null) stack.Push(root.left); } } return result; }
//DFS: 先序 Pre-order Traversal, Stack public List<int> PreOrderTraversal_Iterative2(TreeNode root) { List<int> result = new List<int>(); Stack<TreeNode> stack = new Stack<TreeNode>(); while (root != null || stack.Count != 0) { if (root != null) { //Store root value first. result.Add(root.val); //Push right child into stack stack.Push(root.right); //Iterate left child first. root = root.left; } else { //if left child does not exist anymore, iterate the nearest right child. root = stack.Pop(); } } return result; }
//DFS: 后序 Post-order Traversal, (Reversed Pre-order Traversal) public List<int> PostOrderTraversal_Iterative2(TreeNode root) { List<int> result = new List<int>(); //Iterative: Reverse Pre-Order Traversal. Stack<TreeNode> stack = new Stack<TreeNode>(); while (root != null || stack.Count != 0) { if (root != null) { result.Add(root.val); if (root.left != null) stack.Push(root.left); root = root.right; } else { root = stack.Pop(); } } result.Reverse(); return result; }
//DFS: 后序 Post-order Traversal, Stack public List<int> PostOrderTraversal_Iterative1(TreeNode root) { //Postorder traversal is more complicated to implement comparing to Preorder and Inorder. //At what point shall we visit the root node: //Condition 1: The root node has no child at all. //Condition 2: The root's child has already been visited. List<int> result = new List<int>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if (root != null) stack.Push(root); TreeNode prev = null; while (stack.Count != 0) { root = stack.Peek(); bool noChild = (root.left == null && root.right == null); bool doneChild = false; if (prev != null && (prev == root.left || prev == root.right)) doneChild = true; //直到没有child了或者child已经访问完了才把栈顶元素出栈 if (noChild || doneChild) { root = stack.Pop(); result.Add(root.val); prev = root; } else { if (root.right != null) stack.Push(root.right); if (root.left != null) stack.Push(root.left); } } return result; }
//DFS: 中序 In-order Traversal, Stack public List<int> InOrderTraversal_Iterative1(TreeNode root) { //Step 1: Iterate left subtree, push left node into stack. //Step 2: Stop push until node is null (its parent has no left child). //Step 3: Pop current node, store the value. //Step 4: Switch to the right subtree and iterate right subtree, List<int> result = new List<int>(); Stack<TreeNode> stack = new Stack<TreeNode>(); //Stop loop when both root is null and stack is empty. while (root != null || stack.Count != 0) { if (root != null) { //Store root for later use stack.Push(root); //Iterate left child first. root = root.left; } else { //If left child does not exist anymore, extract its parent root = stack.Pop(); //And store parent value result.Add(root.val); //Then iterate its right child. root = root.right; } } return result; }
public void GetMinimum_Returns_Zero_For_Empty_Stack() { DataStructures.Stack stack = new DataStructures.Stack(); Assert.AreEqual(0, stack.GetMinimumItem()); }
public void Adding_An_Item_To_Stack_Changes_Minimum_Count() { DataStructures.Stack stack = new DataStructures.Stack(); stack.Push(2); Assert.AreEqual(2, stack.GetMinimumItem()); }
public int solution(string S) { int minInteger = 0; int maxInteger = (1 << 20) - 1; Stack<int> stack = new Stack<int>(); foreach (string op in S.Split(' ')) { if (op == "DUP") { if (!stack.Any()) { return -1; } stack.Push(stack.Peek()); } else if (op == "POP") { if (!stack.Any()) { return -1; } stack.Pop(); } else if (op == "+") { if (stack.Count() < 2) { return -1; } var top = stack.Pop(); var nextTop = stack.Pop(); var sum = top + nextTop; if (sum > maxInteger) { // Overflow return -1; } stack.Push(sum); } else if (op == "-") { if (stack.Count() < 2) { return -1; } var top = stack.Pop(); var nextTop = stack.Pop(); var diff = top - nextTop; if (diff < minInteger) { // Overflow return -1; } stack.Push(diff); } else { int number; if (!int.TryParse(op, out number)) { return -1; } if (number < minInteger || number > maxInteger) { return -1; } stack.Push(number); } } if (!stack.Any()) { return -1; } return stack.Pop(); }
static void Main(string[] args) { // Instantiate an instance of each generic collection classes List <string> princesses = new List <string>(); LinkedList <string> moviesThatMadeMeCry = new LinkedList <string>(); Queue <string> resturantOrders = new Queue <string>(); Stack <string> dishesToWash = new Stack <string>(); Dictionary <string, string> codeNames = new Dictionary <string, string>(); SortedList <string, double> resturantRatings = new SortedList <string, double>(); HashSet <string> justiceLeague = new HashSet <string>(); HashSet <string> heroesThatFly = new HashSet <string>(); // Insert 5 values into each collection, iterate over the collection and print each value to console // Print a line above your iteration stating which data structure you're printing from and a blank line between each collection // List Console.WriteLine("List data structure - Disney Princessess:"); foreach (string princess in new string[5] { "Jasmine", "Cinderella", "Snow White", "Rapunzel", "Lilo" }) { princesses.Add(princess); } for (int i = 0; i < princesses.Count; i++) { string princess = princesses[i]; Console.WriteLine(princess); } Console.WriteLine(); // Linked List Console.WriteLine("Linked list data structure - Movies that made me cry:"); foreach (string movie in new string[5] { "Up", "Lion King", "Coco", "Toy Story", "Tangled" }) { moviesThatMadeMeCry.AddFirst(movie); } for (LinkedListNode <string> node = moviesThatMadeMeCry.First; node != null; node = node.Next) { string movie = node.Value; Console.WriteLine(movie); } Console.WriteLine(); // Queue Console.WriteLine("Queue data structure - Resturant Orders:"); foreach (string order in new string[5] { "Tacos", "Bacon Cheese Burger", "Fried Chicken", "Meat-Lovers Pizza", "Nachoes" }) { resturantOrders.Enqueue(order); } foreach (string order in resturantOrders) { Console.WriteLine(order); } Console.WriteLine(); // Stack Console.WriteLine("Stack data structure - Dishes to wash:"); foreach (string dish in new string[5] { "Plate", "Bowl", "Plate", "Spoon", "Bowl" }) { dishesToWash.Push(dish); } foreach (string dish in dishesToWash) { Console.WriteLine(dish); } Console.WriteLine(); // Dictionary Console.WriteLine("Dictionary data structure - Agent Code Names:"); codeNames["Bruce Wayne"] = "Batman"; codeNames["Steve Rogers"] = "Captain America"; codeNames["David Bruce Banner"] = "Incredible Hulk"; codeNames["Clark Kent"] = "Superman"; codeNames["Barry Allen"] = "The Flash"; foreach (var element in codeNames) { string name = element.Key; string code = element.Value; Console.WriteLine($"Name: {name}, Code Name: {code}"); } Console.WriteLine(); // Sorted List Console.WriteLine("Sorted list data structure - Resturant Ratings:"); resturantRatings.Add("Nacho Business", 3.5); resturantRatings.Add("Tequila Mockingbird", 4.0); resturantRatings.Add("Not Another Buger Place", 4.5); resturantRatings.Add("Thai Tanic", 4.0); resturantRatings.Add("Frying Nemo", 5.0); foreach (KeyValuePair <string, double> element in resturantRatings) { string name = element.Key; double rating = element.Value; Console.WriteLine($"Name: {name}, Rating: {rating}"); } Console.WriteLine(); // Hash Set Console.WriteLine("Hash set data structure-"); justiceLeague.Add("Superman"); justiceLeague.Add("Batman"); justiceLeague.Add("Wonder Woman"); justiceLeague.Add("Cyborg"); justiceLeague.Add("The Flash"); heroesThatFly.Add("Superman"); heroesThatFly.Add("Cyborg"); heroesThatFly.Add("Green Lantern"); heroesThatFly.Add("Shazam"); heroesThatFly.Add("Storm"); Console.WriteLine("Justice League Members (Snyder's Cut):"); foreach (string hero in justiceLeague) { Console.WriteLine(hero); } Console.WriteLine(); Console.WriteLine("Super Heroes that fly:"); foreach (string hero in heroesThatFly) { Console.WriteLine(hero); } Console.WriteLine(); Console.WriteLine("Justice League members that can fly:"); justiceLeague.IntersectWith(heroesThatFly); foreach (string hero in justiceLeague) { Console.WriteLine(hero); } }
static void Main(string[] args) { List<int> myList = new List<int>(); myList.Append(1); myList.Append(2); myList.Append(3); Console.WriteLine(myList); myList = new List<int>(3, 2, 1); Console.WriteLine(myList); myList = new List<int>(new System.Collections.Generic.List<int>(new int[] { 4, 3, 2, 1 })); Console.WriteLine(myList); Console.WriteLine(myList.Length); Console.WriteLine(myList.Count()); myList.AppendRange(new System.Collections.Generic.List<int>(new int[] { 4, 3, 2, 1 })); Console.WriteLine(myList); Console.WriteLine(myList.Length); Console.WriteLine(myList.Count()); Console.WriteLine(myList.ElementAt(2)); Console.WriteLine(myList.ElementAt(3)); Console.WriteLine(myList.IndexOf(3)); myList = new List<int>(10, 20, 30, 40); myList.Insert(0, 8); Console.WriteLine(myList); myList = new List<int>(10, 20, 30, 40); myList.Insert(1, 8); Console.WriteLine(myList); myList = new List<int>(10, 20, 30, 40); myList.Insert(2, 8); Console.WriteLine(myList); myList = new List<int>(10, 20, 30, 40); myList.Insert(4, 8); Console.WriteLine(myList); myList = new List<int>(10, 20, 30, 40); myList.Insert(3, 7, 8, 9); Console.WriteLine(myList); myList.Remove(7); Console.WriteLine(myList); myList.Remove(10); Console.WriteLine(myList); myList.Remove(40); Console.WriteLine(myList); myList.Remove(9); Console.WriteLine(myList); myList.RemoveAt(1); Console.WriteLine(myList); myList.RemoveAt(1); Console.WriteLine(myList); myList = new List<int>(10, 20, 30, 40); Console.WriteLine(myList); myList.Sort(); Console.WriteLine(myList); myList = new List<int>(2, 3, 1, 4); Console.WriteLine(myList); myList.Sort(); Console.WriteLine(myList); myList = new List<int>(4, 3, 2, 1); Console.WriteLine(myList); myList.Sort(); Console.WriteLine(myList); Random rand = new Random(); //static seed! for (int i = 0; i < 20; i++) { myList = new List<int>(); for (int j = 0; j < i; j++) myList.Append(rand.Next() % 100); Console.WriteLine(myList); myList.Sort(); Console.WriteLine(myList); Console.WriteLine(); } myList = new List<int>(4, 3, 2, 1); foreach (int item in myList) Console.WriteLine(item); Console.WriteLine(myList[0]); myList[1] = 8; Console.WriteLine(myList[1]); Console.WriteLine(myList[2]); Console.WriteLine(myList[3]); myList.RemoveAt(0); myList.RemoveAt(0); myList.RemoveAt(0); myList.RemoveAt(0); foreach (int item in myList) Console.WriteLine(item); Stack<int> myStack = new Stack<int>(1, 2, 3); Console.WriteLine(myStack); myStack.push(2); Console.WriteLine(myStack); Console.WriteLine(myStack.pop().ToString()); Console.WriteLine(myStack); myStack.push(5); myStack.push(4); myStack.Sort(); Console.WriteLine(myStack); Queue<int> myQueue = new Queue<int>(1, 2, 3); Console.WriteLine(myQueue); myQueue.enqueue(2); Console.WriteLine(myQueue); Console.WriteLine(myQueue.dequeue().ToString()); Console.WriteLine(myQueue); myQueue.enqueue(5); myQueue.enqueue(4); myQueue.Sort(); Console.WriteLine(myQueue); foreach (int item in myQueue) { Console.Write(item); } Console.WriteLine(); System.Collections.Generic.List<int> theirList = new System.Collections.Generic.List<int>(); theirList.Add(1); theirList.Add(1); theirList.Add(1); theirList.Add(1); var exit = Console.Read(); //DEBUG pause }