void FixedCapacityStackTest() { //string[] str = new string[13] { "To", "be", "or", "not", "to", "-", "be", "-", "-", "that", "-", "-", "-" }; int[] array = new int[13] { 00, -1, 22, 33, 44, -1, 66, 77, 88, 99, -1, 110, 120 }; //FixedCapacityStack<string> stringStack = new FixedCapacityStack<string>(100); FixedCapacityStack <int> intStack = new FixedCapacityStack <int>(100); //stringStack........................................... //for (int i = 0; i < str.Length; i++) //{ // string item = str[i]; // if (!item.Equals("-")) // { // stringStack.Push(item); // print("+" + item); // } // else if (!stringStack.IsEmpty()) print("-" + stringStack.POP()); //} //for (int i = 0; i < stringStack.N; i++) //{ // print("Remain stringStack item:" + stringStack.a[i]); //} //intStack........................................... for (int i = 0; i < array.Length; i++) { int item = array[i]; if (item != -1) { intStack.Push(item); print("+" + item); } else if (!intStack.IsEmpty()) { print("-" + intStack.POP()); } } for (int i = 0; i < intStack.N; i++) { print("Remain intStack item:" + intStack.a[i]); } }
/// <summary> /// 定长 Stack 的一个应用: 倒序输出某个序列 /// </summary> static void FixedCapacityStackClient() { var arr = new String[] { "h1", "h2", "h3", "h4", "h5" }; var stack = new FixedCapacityStack <String>(arr.Length); foreach (var item in arr) { stack.Push(item); } // 实现了迭代器之后, 就可以直接在 stack 上遍历了(这里实现的是一个逆序迭代器) foreach (var item in stack) { System.Console.WriteLine($"栈中元素: {item}"); } while (!stack.IsEmpty()) { System.Console.WriteLine(stack.Pop()); } }
/// <summary> /// 返回对 n 个随机整数的栈进行 n 次 push 和 n 次 pop 所需的时间。 /// </summary> /// <param name="n">随机数组的长度。</param> /// <returns></returns> public static double TimeTrialGeneric(int n) { var a = new int[n]; var stack = new FixedCapacityStack <int>(n); var random = new Random(DateTime.Now.Millisecond); for (var i = 0; i < n; i++) { a[i] = random.Next(-MaximumInteger, MaximumInteger); } var timer = new Stopwatch(); for (var i = 0; i < n; i++) { stack.Push(a[i]); } for (var i = 0; i < n; i++) { stack.Pop(); } return(timer.ElapsedTimeMillionSeconds()); }