1. BCL中顺序栈
BCL中有Stack,实现了栈的操作。
1.1 Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _402_栈 { class Program { static void Main(string[] args) { //1.使用BCL中的Stack<T> Stack<char> stack = new Stack<char>(); stack.Push('2'); stack.Push('6'); stack.Push('f'); stack.Push('h'); Console.WriteLine("Push 后的个数" + stack.Count); Console.WriteLine("Pop之前的stack元素:"); foreach (var temp in stack) { Console.Write(temp + " "); } char c = stack.Pop();//取得栈顶数据,并将该数据删除 Console.WriteLine("Pop之后得到的数据:" + c); Console.WriteLine("Pop之后的stack元素:"); foreach (var temp in stack) { Console.Write(temp + " "); } char c2 = stack.Peek();//取得栈顶元素,不删除 Console.WriteLine("peek得到的数据:" + c2); Console.WriteLine("peek后栈中元素个数:" + stack.Count); stack.Clear(); Console.WriteLine("Clear后栈中元素个数:" + stack.Count); //Console.WriteLine("空栈时取栈顶元素:" + stack.Peek());//为空栈时不能取栈顶元素,即不能进行peek pop操作,会出错 Console.ReadKey(); } } }
2. 自己实现顺序栈
定义一个顺序栈的接口IStackDS,再实现接口中的方法。
2.1 IStackDS.cs(接口)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _402_栈
{
interface IStackDS<T>
{
int Count { get; }//用来取得数据
int GetLength();
bool IsEmpty();
void Clear();
void Push(T item);
T Peek();
T Pop();
}
}
2.2 SeqStack.cs(实现接口)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _402_栈
{
class SeqStack<T> : IStackDS<T>
{
private T[] data;
private int top;
public SeqStack(int size)
{
data = new T[size];
top = -1;
}
public SeqStack():this(10)
{
}
public int Count {
get
{
return top + 1;
}
}
public void Clear()
{
top = -1;
}
public int GetLength()
{
return Count;
}
public bool IsEmpty()
{
return top == -1;
}
public T Peek()
{
return data[top];
}
public T Pop()
{
T temp = data[top];
top--;
return temp;
}
public void Push(T item)
{
data[top + 1] = item;
top++;
}
}
}
2.3 Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _402_栈 { class Program { static void Main(string[] args) { //2.使用自己定义的顺序栈 IStackDS<char> stack = new SeqStack<char>(30); stack.Push('2'); stack.Push('6'); stack.Push('f'); stack.Push('h'); Console.WriteLine("Push 后的个数" + stack.Count); char c = stack.Pop();//取得栈顶数据,并将该数据删除 Console.WriteLine("Pop之后得到的数据:" + c); char c2 = stack.Peek();//取得栈顶元素,不删除 Console.WriteLine("peek得到的数据:" + c2); Console.WriteLine("peek后栈中元素个数:" + stack.Count); stack.Clear(); Console.WriteLine("Clear后栈中元素个数:" + stack.Count); Console.ReadKey(); } } }