棧是**限制在表尾進行插入/刪除**的線性表,遵循 **LIFO (後進先出)** 原則:
IStack<T>繼承通用數據結構接口 IDS<T>(Count/IsEmpty/Clear),新增棧專有操作:
public interface IStack : IDS {
void Push(T item); // 入棧
T Pop(); // 出棧(移除並返回頂部元素)
T GetTop(); // 取棧頂元素(不移除)
}
SeqStack<T>基於**動態數組**實現,封裝核心字段:
private T[] data; // 存儲數據
private int maxSize; // 容量上限
private int top; // 棧頂指針,-1 表示空棧
public SeqStack() : this(10) { } // 默認容量 10
public SeqStack(int size) {
data = new T[size];
maxSize = size;
top = -1;
}
Pushpublic void Push(T item) {
if (top == maxSize - 1) {
Console.WriteLine("棧已滿");
return; // 或拋出異常/擴容
}
data[++top] = item; // 先遞增指針,再賦值
}
Poppublic T Pop() {
if (top == -1) {
Console.WriteLine("棧為空");
return default(T);
}
return data[top--]; // 先取值,後遞減指針
}
GetToppublic T GetTop() {
if (top == -1) {
Console.WriteLine("棧為空!");
return default(T);
}
return data[top];
}
// 判滿
public bool IsFull => top == maxSize - 1;
// IDS 成員
public int Count => top + 1;
public void Clear() => top = -1;
public bool IsEmpty => top == -1;
// 索引器(僅供調試/遍歷,破壞封裝慎用)
public T this[uint index] {
get => data[index];
set => data[index] = value;
}
namespace DataStructures {
public interface IDS {
int Count { get; }
void Clear();
bool IsEmpty { get; }
}
public interface IStack : IDS {
void Push(T item);
T Pop();
T GetTop();
}
public class SeqStack : IStack {
// 字段、構造函數、屬性、Push/Pop/GetTop、IDS 實現
// 見上文完整實現
}
}
var stack = new SeqStack(3);
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine(stack.IsFull); // True
Console.WriteLine(stack.GetTop()); // 3
Console.WriteLine(stack.Pop()); // 3
Console.WriteLine(stack.Count); // 2
stack.Clear();
Console.WriteLine(stack.IsEmpty); // True
Array.Copy 遷移(參考 List<T> 實現)。ThrowHelper.ThrowInvalidOperationException() 替代 Console.WriteLine。IEnumerable<T>:支持 foreach 遍歷(從棧頂到棧底)。ConcurrentStack<T> (System.Collections.Concurrent) 已提供無鎖實現。System.Collections.Generic.Stack<T>| 特性 | SeqStack (教學) | BCL Stack<T> |
|---|---|---|
| 底層存儲 | 固定/手動擴容數組 | 動態擴容數組 |
| 異常處理 | 返回 default/控制台輸出 | 拋出 InvalidOperationException |
| 擴容策略 | 無/需手動實現 | 2倍擴容 |
| 枚舉順序 | 需自行實現 | 棧頂→棧底 |
| 線程安全 | 無 | 無 (有 ConcurrentStack) |