数组栈
接口代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
interface IStack<E>
{
int Count {
get; }
bool IsEmpty {
get; }
void Push(E e);
E Pop();
E Peek();
}
}
数组栈类代码:此处调用的方法为为之前所写数组类方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class Array1Stack<E> : IStack<E>
{
private Array1<E> arr;
public int Count
{
get {
return arr.Count; }
}
public bool IsEmpty
{
get {
return arr.IsEmpty; }
}
public Array1Stack(int capacity)//构造函数
{
arr = new Array1<E>(capacity);
}
public Array1Stack()//没有参数就自动扩容
{
arr = new Array1<E>();
}
public void Push(E e)
{
arr.AddLast(e);//选择数组的尾部作为栈顶,此处调用的方法为为之前所写数组类方法
}
public E Pop()
{
return arr.RemoveLast();//按照删除数组尾部元素作为出栈
}
public E Peek()//查询栈顶元素
{
return arr.GetLast();
}
public override string ToString()
{
return "Stack:" + arr.ToString() + "top";
}
}
}
主程序代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class Program
{
static void Main(string[] args)
{
Array1Stack<int> stack = new Array1Stack<int>();
for(int i=0;i<5;i++)
{
stack.Push(i);
Console.WriteLine(stack);
}
stack.Pop();
Console.WriteLine(stack);
Console.Read();
}
}
}
链表栈
链表栈类代码:所用接口为上面数组栈所添加的接口Istack,方法为上节所写的链表类方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class LinkedList1Stack<E>:IStack<E>//使用链表类封装一个链表栈
{
private LinkedList1<E> list;
public LinkedList1Stack()
{
list = new LinkedList1<E>();
}
public int Count
{
get {
return list.Count; }
}
public bool IsEmpty
{
get {
return list.IsEmpty; }
}
public E Peek()
{
return list.GetFirst();
}
public E Pop()
{
return list.RemoveFirst();
}
public void Push(E e)
{
list.AddFirst(e);//以链表头部作为栈顶
}
public override string ToString()//打印输出方法
{
return "Stack:top" + list.ToString();
}
}
}
主程序代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class Program
{
static void Main(string[] args)
{
LinkedList1Stack<int> stack = new LinkedList1Stack<int>();
for (int i = 0; i < 5; i++)
{
stack.Push(i);
Console.WriteLine(stack);
}
stack.Pop();
Console.WriteLine(stack);
Console.Read();
}
}
}
结果
Stack:top0->Null
Stack:top1->0->Null
Stack:top2->1-