1. 链栈
定义一个结点类,包含数据域和指针域,并定义构造方法;定义了一个接口,再实现接口。
1.1 Node.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _402_栈
{
/// <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> next)
{
this.data = data;
this.next = next;
}
public Node(Node<T> next)
{
data = default(T);
this.next = next;
}
public T Data
{ get
{
return data;
}
set
{
data = value;
}
}
public Node<T> Next{
get
{
return next;
}
set
{
next = value;
}
}
}
}
1.2 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();
}
}
1.3 LinkStack.cs(实现接口)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _402_栈
{
class LinkStack<T> : IStackDS<T>
{
public Node<T> top;//栈顶
public int count;//计数器,记录栈中数据个数
/// <summary>
/// 链栈中数据个数
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// 清空链栈
/// </summary>
public void Clear()
{
count = 0;
}
/// <summary>
/// 得到链栈长度
/// </summary>
/// <returns></returns>
public int GetLength()
{
return count;
}
/// <summary>
/// 链栈是否为空
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return count == 0;
}
/// <summary>
/// 取得链栈栈顶元素,但不删除
/// </summary>
/// <returns></returns>
public T Peek()
{
return top.Data;
}
/// <summary>
/// 取得链栈栈顶元素并删除
/// </summary>
/// <returns></returns>
public T Pop()
{
T item = top.Data;
top = top.Next;
count--;
return item;
}
/// <summary>
/// 元素入栈
/// </summary>
/// <param name="item"></param>
public void Push(T item)
{
Node<T> newNode = new Node<T>(item);
newNode.Next = top;
top = newNode;
count++;
}
}
}
1.4 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)
{ //3.使用自己定义的链栈
IStackDS<char> stack = new LinkStack<char>();
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();
}
}
}