C#数据结构之堆栈(Stack)实例详解

2019-12-30 11:22:56于丽

链式堆栈(LinkStack)的实现

先定义节点Node.cs


namespace 栈与队列
{
  public class Node<T>
  {
    private T data;
    private Node<T> next;
    public Node(T data, Node<T> next) 
    {
      this.data = data;
      this.next = next;
    }
    public Node(Node<T> next) 
    {
      this.next = next;
      this.data = default(T);
    }
    public Node(T data) 
    {
      this.data = data;
      this.next = null;
    }
    public Node() 
    {
      this.data = default(T);
      this.next = null;
    }
    public T Data {
      get { return this.data; }
      set { this.data = value; }
    }
    public Node<T> Next 
    {
      get { return next; }
      set { next = value; }
    }
  }
}

下面是LinkStack.cs


using System;
using System.Text;
namespace 栈与队列
{
  public class LinkStack<T>:IStack<T>
  {
    private Node<T> top;
    private int num;//节点个数
    /// <summary>
    /// 顶部节点
    /// </summary>
    public Node<T> Top 
    {
      get { return top; }
      set { top = value; }
    }
    public LinkStack() 
    {
      top = null;
      num = 0;
    }
    public int Count() 
    {
      return num;
    }
    public void Clear() 
    {
      top = null;
      num = 0;
    }
    public bool IsEmpty() 
    {
      if (top == null && num == 0)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    public void Push(T item) 
    {
      Node<T> q = new Node<T>(item);
      if (top == null)
      {
        top = q;
      }
      else
      {
        q.Next = top;
        top = q;
      }
      num++;
    }
    public T Pop() 
    {
      if (IsEmpty()) 
      {
        Console.WriteLine("Stack is empty!");
        return default(T);
      }
      Node<T> p = top;
      top = top.Next;
      num--;
      return p.Data;
    }
    public T Peek() 
    {
      if (IsEmpty()) 
      {
        Console.WriteLine("Stack is empty!");
        return default(T);
      }
      return top.Data;
    }
    public override string ToString()
    {
      StringBuilder sb = new StringBuilder();
      if (top != null) 
      {
        sb.Append(top.Data.ToString() + ",");
        Node<T> p = top;
        while (p.Next != null)
        {          
          sb.Append(p.Next.Data.ToString()+ ",");
          p = p.Next;
        }
      }
      return sb.ToString();
    }
  }
}

测试代码片段:


Console.WriteLine("顺序堆栈测试开始...");
SeqStack<int> seqStack = new SeqStack<int>(10);
seqStack.Push(1);
seqStack.Push(2);
seqStack.Push(3);
Console.WriteLine(seqStack);
Console.WriteLine(seqStack.Peek());
Console.WriteLine(seqStack);
Console.WriteLine(seqStack.Pop());
Console.WriteLine(seqStack);
Console.WriteLine("链堆栈测试开始...");
LinkStack<int> linkStack = new LinkStack<int>();
linkStack.Push(1);
linkStack.Push(2);
linkStack.Push(3);
Console.WriteLine(linkStack);
Console.WriteLine(linkStack.Peek());
Console.WriteLine(linkStack);
Console.WriteLine(linkStack.Pop());
Console.WriteLine(linkStack);
Console.ReadLine();