链栈
用带有头节点的单链表实现的栈。
用头节点当栈顶指针。
当top.Next==null时,栈空。
实现
Node
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkStack
{
class Node<T>
{
T data;
Node<T> next;
/// <summary>
/// 构造器
/// </summary>
public Node()
{
this.Data = default(T);
this.Next = null;
}
/// <summary>
/// 构造器
/// </summary>
/// <param name="data"></param>
public Node(T data)
{
this.Data = data;
}
public T Data { get => data; set => data = value; }
internal Node<T> Next { get => next; set => next = value; }
}
}
LinkStack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkStack
{
class LinkStack<T>
{
Node<T> top;
public LinkStack()
{
this.top = new Node<T>();
}
/// <summary>
/// 入栈
/// </summary>
/// <param name="data"></param>
public void Push(T data)
{
//新建节点
Node<T> tmp = new Node<T>(data);
//挂载节点
tmp.Next = this.top.Next;
this.top.Next = tmp;
}
/// <summary>
/// 出栈
/// </summary>
/// <returns></returns>
public T Pop()
{
if (top.Next == null) return default(T);
//保存栈顶节点
Node<T> tmp = top.Next;
//悬空栈顶节点
top.Next = top.Next.Next;
return tmp.Data;
}
}
}
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkStack
{
class Program
{
static void Main(string[] args)
{
LinkStack<string> ls = new LinkStack<string>();
ls.Push("a");
ls.Push("b");
ls.Push("c");
ls.Push("d");
for (int i = 0; i < 4; i++)
{
Console.WriteLine(ls.Pop());
}
}
}
}
网友评论