namespace 栈{ interface IStackDS<T> { int Count { get; } int GetLength(); bool IsEmpty(); void Clear(); void Push(T item); T Pop(); T Peek(); }}
顺序栈的实现,参照顺序表实现
namespace 栈{ 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) { data = new T[10]; top = -1; } //栈的元素个数属性 public int Count { get { return top + 1; } } //清空栈的方法 public void Clear() { top = -1; } //获取栈的长度的方法 public int GetLength() { return Count; } //查看栈顶元素是什么 public T Peek() { if (top == -1) { Console.WriteLine("当前栈没有元素"); return default(T); } return data[top]; } //出栈(取出栈顶元素,并移除) public T Pop() { T temp = data[top]; top--; return temp; } //入栈 public void Push(T item) { data[top + 1] = item; top++; } //栈中是否源元素 public bool IsEmpty() { return Count==0; } }}
以上是顺序栈的实现
下面是链栈的实现,定义一个节点类
namespace 栈{ /// <summary> /// 链栈的节点 /// </summary> /// <typeparam name="T"></typeparam> class Node<T> { private T data; //数据 private Node<T> next; //指向下一个的引用 //四个构造函数,不是都有用,,以及上面两个变量的属性, public Node() { data = default(T); next = null; } public Node(T data) { this.data = data; next = null; } public Node(T data , Node<T> index) { this.data = data; this.next = index; } public Node(Node<T> index) { data = default(T); next = index; } public T Data { get { return data; } set { data = value; } } public Node<T> Next { get { return next; } set { next = value; } } }}
链栈的实现:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 栈{ class LinkStark<T> : IStackDS<T> { private Node<T> top; //栈顶元素节点 private int count = 0; //栈里面的元素 public int Count { get { return count; } } /// <summary> /// 清空栈中数据 /// </summary> public void Clear() { count = 0; top = null; } /// <summary> /// 栈的长度 /// </summary> /// <returns></returns> public int GetLength() { return Count; } /// <summary> /// 栈中是否有数据 /// </summary> /// <returns></returns> public bool IsEmpty() { return count == 0; } public T Peek() { return top.Data; } /// <summary> /// 出栈 取得栈顶元素然后删除 /// </summary> /// <returns></returns> public T Pop() { T data = top.Data; top = top.Next; count--; return data; } /// <summary> /// 入栈 /// </summary> /// <param name="item"></param> public void Push(T item) {//把新添加的元素作为头结点,就是栈顶 Node<T> newNode = new Node<T>(item); newNode.Next = top; top = newNode; count++; } }}