C#數(shù)據(jù)結(jié)構(gòu):順序棧
-
1殴蓬、自定義順序棧結(jié)構(gòu):
/// <summary>
/// 順序棧
/// </summary>
/// <typeparam name="T"></typeparam>
public class SeqStack<T>
{
private T[] data;
private int top; ///*用來存放棧頂元素的下標(biāo)匿级,top 為-1 表示空棧*/
public SeqStack(int size)
{
data = new T[size];
top = -1;
}
public SeqStack() : this(10)//默認(rèn)構(gòu)造函數(shù),最大容量10
{
}
//棧最大容量
public int MaxSize
{
get
{
return data.Length;
}
}
//判空
public bool IsEmpty()
{
return top == -1;
}
//判滿
public bool IsFull()
{
return top == data.Length - 1;
}
//進(jìn)棧
public void Push(T item)
{
if(IsFull())
{
Debug.LogError("棧滿染厅!");
return;
}
data[++top] = item;
}
//出棧
public T Pop()
{
if(IsEmpty())
{
Debug.LogError("椂灰铮空,無法出棧肖粮!");
return default(T);
}
return data[top--];
}
//訪問棧頂
public T Peek()
{
if (IsEmpty())
{
Debug.LogError("椆乱常空,無法訪問棧頂涩馆!");
return default(T);
}
return data[top];
}
//棧中元素個數(shù)
public int Count
{
get
{
return top + 1;
}
}
//清空棧
public void Clear()
{
top = -1;
}
}
順序棧:測試用例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class _005_SeqStack : MonoBehaviour
{
SeqStack<string> seqStack;
void Start()
{
//初始化棧
seqStack = new SeqStack<string>(4);//size=4
//棧最大容量
Debug.Log("棧最大容量:" + seqStack.MaxSize);
//判空
Debug.Log("棧是否空:" + seqStack.IsEmpty());
//判滿
Debug.Log("棧是否滿:" + seqStack.IsFull());
//進(jìn)棧
Debug.Log("進(jìn)棧:" + "1,2,3,4");
seqStack.Push("1");
seqStack.Push("2");
seqStack.Push("3");
seqStack.Push("4");
//棧中元素個數(shù)
Debug.Log("棧中元素個數(shù): " + seqStack.Count);
//判滿
Debug.Log("棧是否滿:" + seqStack.IsFull());
//出棧
Debug.Log("出棧-----出棧值為:" + seqStack.Pop());
//棧中元素個數(shù)
Debug.Log("出棧后行施,棧中元素個數(shù): " + seqStack.Count);
//訪問棧頂元素
Debug.Log("棧頂元素值: " + seqStack.Peek());
//棧中元素個數(shù)
Debug.Log("訪問棧頂后,棧中元素個數(shù): " + seqStack.Count);
//清空棧
seqStack.Clear();
Debug.Log("清空棧魂那!");
//棧中元素個數(shù)
Debug.Log("清空棧后蛾号,棧中元素個數(shù): " + seqStack.Count);
}
}
輸出結(jié)果:
img.jpg
注意:
1、棧也是表結(jié)構(gòu)涯雅,只是限制了表的操作位置鲜结,棧的操作只能在棧頂。
2活逆、棧是先進(jìn)后出精刷。
3.訪問棧頂?shù)腜eek()操作,不會改變棧頂指針蔗候。