之前研究过怎么自定义自己的栈,现在附上源码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MYSTACK
{
class Node<T>
{
private T mData;
public T Data
{
get
{
return mData;
}
}
//此节点的下一个节点
public Node<T> mNext;
public Node(T num) {
mData = num;
mNext = null;
}
}
class MyStack<T>
{
private int mCount;
public int Count {
get {
return mCount;
}
}
//栈顶节点
public Node<T> mTop;
public MyStack()
{
mTop = null;
}
public void Push(T num) {
if (mCount == 0)
mTop = new Node<T> (num);
else {
Node<T> no = new Node<T> (num);
no.mNext = mTop;
mTop = no;
}
mCount++;
}
public T Pop() {
if (mCount <= 0)
return default(T); //default会自动选择,值类型返回0,引用类型返回null
Node<T> no = mTop;
if (Count == 1)
mTop = null;
else
mTop = mTop.mNext;
mCount--;
return no.Data;
}
}
public class Test:MonoBehaviour{
void Start ()
{
MyStack<int> stack1 = new MyStack<int> ();
stack1.Push (1);
stack1.Push (2);
stack1.Push (3);
int lenth = stack1.Count;
for (int i = 0; i < lenth; i++) {
Debug.LogError (stack1.Pop ());
}
}
}
}
只写了入栈Push和出栈Pop这两个方法,方法都一样其他就不写出来了(懒)。