2022-12-23 18:28:17 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: stack.cs
|
|
|
|
|
* Created Time: 2022-12-23
|
|
|
|
|
* Author: haptear (haptear@hotmail.com)
|
|
|
|
|
*/
|
2022-12-23 15:42:02 +08:00
|
|
|
|
|
|
|
|
|
using NUnit.Framework;
|
|
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
|
namespace hello_algo.chapter_stack_and_queue;
|
|
|
|
|
|
|
|
|
|
public class stack
|
2022-12-23 15:42:02 +08:00
|
|
|
|
{
|
2023-02-08 22:18:02 +08:00
|
|
|
|
[Test]
|
|
|
|
|
public void Test()
|
2022-12-23 15:42:02 +08:00
|
|
|
|
{
|
2023-02-08 22:18:02 +08:00
|
|
|
|
/* 初始化栈 */
|
|
|
|
|
Stack<int> stack = new();
|
|
|
|
|
|
|
|
|
|
/* 元素入栈 */
|
|
|
|
|
stack.Push(1);
|
|
|
|
|
stack.Push(3);
|
|
|
|
|
stack.Push(2);
|
|
|
|
|
stack.Push(5);
|
|
|
|
|
stack.Push(4);
|
|
|
|
|
// 请注意,stack.ToArray() 得到的是倒序序列,即索引 0 为栈顶
|
2023-04-21 14:59:22 +08:00
|
|
|
|
Console.WriteLine("栈 stack = " + string.Join(",", stack));
|
2023-02-08 22:18:02 +08:00
|
|
|
|
|
|
|
|
|
/* 访问栈顶元素 */
|
|
|
|
|
int peek = stack.Peek();
|
|
|
|
|
Console.WriteLine("栈顶元素 peek = " + peek);
|
|
|
|
|
|
|
|
|
|
/* 元素出栈 */
|
|
|
|
|
int pop = stack.Pop();
|
2023-04-21 14:59:22 +08:00
|
|
|
|
Console.WriteLine("出栈元素 pop = " + pop + ",出栈后 stack = " + string.Join(",", stack));
|
2023-02-08 22:18:02 +08:00
|
|
|
|
|
|
|
|
|
/* 获取栈的长度 */
|
|
|
|
|
int size = stack.Count();
|
|
|
|
|
Console.WriteLine("栈的长度 size = " + size);
|
|
|
|
|
|
|
|
|
|
/* 判断是否为空 */
|
|
|
|
|
bool isEmpty = stack.Count() == 0;
|
|
|
|
|
Console.WriteLine("栈是否为空 = " + isEmpty);
|
2022-12-23 15:42:02 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
}
|