先进后出,后进先出
void Start ()
{
Stack<char> stack=new Stack<char>();
stack.Push('a');
stack.Push('b');
stack.Push('c'); //栈顶数据
Debug.Log("push a b c数据的个数为:"+stack.Count);
char temp= stack.Pop(); //取得栈顶数据,并把栈顶的数据删除
Debug.Log(temp);
Debug.Log("Pop后的数据个数为:"+stack.Count);
char temp2=stack.Peek(); //取得栈顶的数据,不删除
Debug.Log(temp2);
Debug.Log("Peek后的数据个数为:"+stack.Count);
stack.Clear();
//Debug.Log("空栈的时候,取得栈顶的值:"+stack.Peek());//出现异常,
//当空栈的时候,不能进行Pop,Peek操作,否则会出现异常;
}
顺序栈:
public interface IStackDS<T>
{
int Count { get; }
int GetLength();
void Clear();
bool IsEmpty();
void Push(T item);
T Pop();
T Peek();
}
/自己创建的栈SeqStack
public class SeqStack<T>:IStackDS<T>
{
private T[] data;
private int top;
public SeqStack()
{
data = null;
top = -1;
}
public SeqStack(int size)
{
data=new T[size];
top = -1;
}
public int Count { get { return top + 1; } }
public int GetLength()
{
return Count;
}
public void Clear()
{
top = -1;
}
public bool IsEmpty()
{
return Count==0;
}
public void Push(T item)
{
data[top + 1] = item;
top++;
}
public T Pop()
{
T temp=data[top];
top--;
return temp;
}
public T Peek()
{
return data[top];
}
}
链栈:
public interface IStackDS<T>
{
int Count { get; }
int GetLength();
void Clear();
bool IsEmpty();
void Push(T item);
T Pop();
T Peek();
}
栈的结点:
public class Node<T>
{
private T data;
private Node<T> next;
public Node()
{
data = default(T);
next = null;
}
public Node(T value)
{
this.data = value;
next = null;
}
public Node(T value, Node<T> next)
{
this.data = value;
this.next = next;
}
public Node(Node<T> next)
{
this.next = next;
this.data = default(T);
}
public T Data
{
get { return this.data; }
set { this.data = value; }
}
public Node<T> Next
{
get { return this.next; }
set { this.next = value; }
}
}
//创建我们自己的链栈
public class LinkStack<T> : IStackDS<T>
{
private Node<T> top; //栈顶元素结点
private int count = 0; //栈中的个数
public int Count { get { return count;} }
public int GetLength()
{
return Count;
}
public void Clear()
{
count = 0;
top = null;
}
public bool IsEmpty()
{
return count == 0;
}
public void Push(T item)
{
//把新添加的元素作为栈顶元素结点
Node<T> newNode=new Node<T>(item);
newNode.Next = top;
top = newNode;
count++;
}
public T Pop()
{
T data = top.Data;
top = top.Next;
count--;
return data;
}
public T Peek()
{
return top.Data;
}
}