C# 栈的实现
早前写得栈的实现,基本功能都有。
代码:
/// <summary> /// 栈 /// </summary> public class Stack { private object[] data; //用data数组来储存数据 private int size; //栈的大小 private int top; //top指针 public object this[int loc] { get { return loc >= 0 && loc <= top ? data[loc] : null; } } /// <summary> /// 当前栈中元素个数 /// </summary> public int Length { get { return this.top + 1; } } /// <summary> /// 构造函数 /// </summary> /// <param name="size"></param> public Stack(int size) { if (size>=0) { this.data = new object[size]; this.size = size; this.top = -1; //初始top指针赋-1 } else { this.data = null; this.size = 0; this.top = -1; } } /// <summary> /// 是否空 /// </summary> /// <returns></returns> public bool isEmpty() { return this.top == -1; } /// <summary> /// 是否满 /// </summary> /// <returns></returns> public bool isFull() { return this.top == this.size - 1; } /// <summary> /// 压栈 /// </summary> /// <param name="elem"></param> public void Push(object elem) { if (this.isFull()) { throw new Exception("Stack is full!"); } this.top++; this.data[this.top] = elem; } /// <summary> /// 出栈 /// </summary> /// <returns></returns> public object Pop() { if (this.isEmpty()) { throw new Exception("Stack is empty!"); } object elem = this.data[this.top]; this.top--; return elem; } /// <summary> /// 获取栈顶元素 /// </summary> /// <returns></returns> public object getTop() { if (this.isEmpty()) { throw new Exception("Stack is empty!"); } return this.data[this.top]; } /// <summary> /// 清空 /// </summary> public void Clear() { this.top = -1; } }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步