using System;
using UnityEngine;
/// <summary>
/// 栈
/// </summary>
public class MyStack<T>
{
/// <summary>
/// 栈的实现还是使用数组的方式存储
/// </summary>
public T[] content { get; set; }
public int Count {
get;
private set;
}
public int capacity { get; set; }
/// <summary>
/// 初始化 默认深度
/// </summary>
public MyStack(int capacity)
{
content = new T[capacity];
this.capacity = capacity;
this.Count =0;
}
/// <summary>
/// 压栈
/// </summary>
/// <param name="t"></param>
public virtual void Push(T t)
{
//如果数组满了,则扩容(翻倍扩容)
if (Count+1 > content.Length)
{
//扩容次数为2的指数级
this.capacity *= 2;
T[] newArray = new T[capacity];
//将原内容拷贝到新的数组中 (扩容次数 2的指数级扩容,减少拷贝带来的时间消耗)
Array.Copy(content, 0, newArray, 0, Count);
content = newArray;
}
//写入数组
content[Count++] = t;
}
/// <summary>
/// 取下一个出栈值,但不删除 (偷看下~)
/// </summary>
/// <returns></returns>
public virtual T Peek()
{
if (Count <= 0)
return default(T);
return content[Count-1];
}
/// <summary>
/// 出栈
/// </summary>
/// <returns></returns>
public virtual T Pop()
{
if (Count <= 0)
return default(T);
T t = content[Count-1];
content[Count-1] = default(T);
Count--;
//如果top小于容量的1/4,容量缩小为原来的1/2
if (Count / capacity < 1 / 4)
{
//扩容次数为2的指数级
this.capacity /= 2;
T[] newArray = new T[capacity];
//将原内容拷贝到新的数组中 (扩容次数 2的指数级扩容,减少拷贝带来的时间消耗)
Array.Copy(content, 0, newArray, 0, Count);
content = newArray;
}
return t;
}
public void Clear()
{
if (Count > 0)
{
Count =0;
capacity = 8;
content= new T[capacity];
}
}
//实现该方法是为了 暂不实现 ICollection -
public void ShowAll()
{
for (int i = Count-1; i >= 0; i--)
{
Debug.Log($" {content[i]}");
}
}
}
/// <summary>
/// 异步栈
/// </summary>
public class MySyncStack<T> : MyStack<T>
{
private MyStack<T> myStack;
private object lookObj = new object();
public MySyncStack(int capacity) : base(capacity)
{
}
public override void Push(T value)
{
lock (lookObj)
{
myStack.Push(value);
}
}
public override T Pop()
{
lock (lookObj)
{
return myStack.Pop();
}
}
public override T Peek()
{
lock (lookObj)
{
return myStack.Peek();
}
}
}