栈
LIFO,先进后出。也可以理解为限定性链表,限制表的操纵只在表的终端位置。
实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace stack
{
class cstack<T>
{
int top = -1;
T[] data;
public int Top { get => top; set => top = value; } //栈顶指示器
public T[] Data { get => data; set => data = value; }
/// <summary>
/// 构造器
/// </summary>
public cstack(int length)
{
this.Data = new T[length];
}
/// <summary>
/// 入栈
/// </summary>
/// <param name="d"></param>
public bool Push(T d)
{
//栈满
if (top == data.Length - 1)
{
return false;
}
++top;
data[top] = d;
return true;
}
/// <summary>
/// 出栈
/// </summary>
/// <returns></returns>
public T Pop()
{
//栈空
if (top == -1)
{
return default(T);
}
T d = data[top];
--top;
return d;
}
/// <summary>
/// 读栈顶元素
/// </summary>
/// <returns></returns>
public T ReadTop()
{
if (top == -1) return default(T);
return data[top];
}
/// <summary>
/// 清空栈
/// </summary>
public void Clear()
{
top = -1;
}
}
}
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace stack
{
class Program
{
static void Main(string[] args)
{
cstack<string> cstack = new cstack<string>(10);
cstack.Push("a");
cstack.Push("b");
cstack.Push("c");
cstack.Push("d");
cstack.Push("e");
cstack.Push("f");
//读栈顶
Console.WriteLine(cstack.ReadTop());
//出栈
Console.WriteLine(cstack.Pop());
Console.WriteLine(cstack.Pop());
Console.WriteLine(cstack.Pop());
Console.WriteLine(cstack.Pop());
Console.WriteLine(cstack.Pop());
Console.WriteLine(cstack.Pop());
}
}
}
网友评论