文章目录
栈和队列是计算机中常用的两种数据结构,是操作受限的线性表。栈的插入和删除等操作都在栈顶进行,它是先进后出的线性表。队列的删除、查找等操作在队头进行,而插入操作在队尾进行,它是先进先出的线性表。与线性表一样,栈和队列也有顺序存储与链式存储两种方式。
栈
1: public interface IStack<T> {
2: /// <summary>
3: /// 获取栈的长度
4: /// </summary>
5: int Count { get; }
6:
7: /// <summary>
8: /// 清空栈
9: /// </summary>
10: void Clear();
11:
12: /// <summary>
13: /// 将一个数据压入栈
14: /// </summary>
15: /// <param name="value"></param>
16: void Push(T value);
17:
18: /// <summary>
19: /// 将一个数据弹出栈
20: /// </summary>
21: /// <returns></returns>
22: T Pop();
23:
24: /// <summary>
25: /// 获取栈顶部的数据,但不弹出
26: /// </summary>
27: /// <returns></returns>
28: T Peek();
29: }
顺序栈
1: public class SequenceStack<T> : IStack<T> {
2: private const int Step = 16;
3: private int _capacity;
4: private int _top = -1;
5: private T[] _datas;
6:
7: public SequenceStack() : this(Step) {}
8:
9: public SequenceStack(int capacity) {
10: this._capacity = capacity;
11: this._datas = new T[this._capacity];
12: }
13:
14: public int Count {
15: get { return this._top + 1; }
16: }
17:
18: public void Clear() {
19: this._top = -1;
20: }
21:
22: public void Push(T value) {
23: if(this._top+1>=this._datas.Length) {
24: this._capacity += Step;
25: T[] temps = new T[this._capacity];
26: for(int i = 0; i < this._datas.Length; i++) {
27: temps[i] = this._datas[i];
28: }
29: this._datas = temps;
30: }
31: this._datas[++this._top] = value;
32: }
33:
34: public T Pop() {
35: return this._datas[this._top--];
36: }
37:
38: public T Peek() {
39: return this._datas[this._top];
40: }
41: }
链栈
1: public class StackNode<T> {
2: private StackNode<T> _next;
3: private T _value;
4:
5: public StackNode() : this(default(T), null) {
6: }
7:
8: public StackNode(T value) : this(value, null) {
9: }
10:
11: public StackNode(T value, StackNode<T> next) {
12: this._value = value;
13: this._next = next;
14: }
15:
16: public StackNode<T> Next {
17: get { return this._next; }
18: set { this._next = value; }
19: }
20:
21: public T Value {
22: get { return this._value; }
23: set { this._value = value; }
24: }
25: }
1: public class LinkStack<T> : IStack<T> {
2: private int _count = 0;
3: StackNode<T> _top;
4:
5: public int Count {
6: get { return this._count; }
7: }
8:
9: public void Clear() {
10: this._top = null;
11: this._count = 0;
12: }
13:
14: public void Push(T value) {
15: this._top=new StackNode<T>(value, this._top);
16: this._count++;
17: }
18:
19: public T Pop() {