下面為棧的邏輯實現:
using System;
using System.Collections.Generic;
using System.Text;
namespace DateStructrues
{
/// <summary>
/// 順序棧
/// </summary>
/// <typeparam name="T">泛型</typeparam>
class SeqStack<T> : IStack<T>
{
#region
//
//數組,存入數據
//
private T[] data;
//
//最大值
//
private int maxsize;
//
//棧頂
//
private int top;
/// <summary>
/// <value>
/// 獲取或設置數組元素
/// </value>
/// </summary>
public T[] Data
{
get
{
return data;
}
}
/// <summary>
/// <value>
/// 獲取或設置最大值
/// </value>
/// </summary>
public int Maxsize
{
get
{
return maxsize;
}
set
{
maxsize = value;
}
}
/// <summary>
/// <value>
/// 獲取或設置棧頂元素
/// </value>
/// </summary>
public int Top
{
get
{
return top;
}
set
{
top = value;
}
}
/// <summary>
/// 無參構造器
/// </summary>
public SeqStack() : this(10) { }
/// <summary>
/// 構造器
/// </summary>
/// <param name="size">初始大小</param>
public SeqStack(int size)
{
data = new T[size];
maxsize = size;
top = -1;
}
#endregion
#region Method
/// <summary>
/// 判斷棧是否為滿
/// </summary>
public bool IsFull
{
get
{
return top == maxsize - 1;
}
}
#endregion
#region IStack<T> 成員
/// <summary>
/// 出棧操作
/// 如果data已滿,top = maxsize - 1
/// data[++top] = item
/// </summary>
/// <returns>出棧的元素值</returns>
public T Pop()
{
T tmp = default(T);
//判斷表是否為空
if (top == -1)
{
Console.WriteLine("棧為空");
return tmp;
}
tmp = data[top--];
return tmp;
}
/// <summary>
/// 入棧操作
/// </summary>
/// <param name="item">將入棧的值</param>
public void Push(T item)
{
if (top == maxsize - 1)
{
Console.WriteLine("棧為滿");
return;
}
data[++top] = item;
}
/// <summary>
/// 獲取棧頂元素
/// </summary>
/// <returns>棧頂元素值</returns>
public T GetTop()
{
if (top == -1)
{
Console.WriteLine("棧為空!");
return default(T);
}
return data[top];
}
#endregion
#region IDS<T> 成員
/// <summary>
/// 獲取棧的長度
/// </summary>
public int Count
{
get
{
return top + 1;
}
}
/// <summary>
/// 清空操作
/// </summary>
public void Clear()
{
top = -1;
}
/// <summary>
/// <value>
/// 判斷棧是否為空
/// 如果為top為-1,返回true
/// 否則,返回false
/// </value>
/// </summary>
public bool IsEmpty
{
get
{
return top == -1;
}
}
#endregion
}
}