using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
//定义链表
public class LinkStack
{
public int count { get; set; }//链表的数目
public StackNode top { get; set; }//链表节点
/// <summary>
/// 构造函数,初始化属性值
/// </summary>
public LinkStack()
{
count = 0;
top = null;
}
/// <summary>
/// 添加链表节点
/// </summary>
/// <param name="stackNode">链表节点</param>
public void Push(StackNode stackNode)
{
if (top == null)
{
top = stackNode;
}
else
{
stackNode.next = top;
top = stackNode;
}
count++;
}
/// <summary>
/// 栈顶节点出栈
/// </summary>
/// <returns></returns>
public string Pop()
{
if (IsEmpty())
{
Console.WriteLine("Stack is empty ,sorry!");
return null;
}
StackNode stackNode = top;
top = top.next;
count--;
return stackNode.data;
}
/// <summary>
/// 判断栈是否为空
/// </summary>
/// <returns>布尔</returns>
public bool IsEmpty()
{
if (top==null && count==0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 显示所有节点
/// </summary>
/// <returns>所有节点【string类型】</returns>
public string ShowStack()
{
StringBuilder sb = new StringBuilder();
if (IsEmpty())
{
Console.WriteLine("Stack is empty ,sorry!");
return null;
}
else {
sb.Append(top.data.ToString() + ",");
StackNode stackNode = top;
while (stackNode.next != null)
{
sb.Append(stackNode.next.data + ",");
stackNode = stackNode.next;
}
}
return sb.ToString();
}
}
/// <summary>
/// 定义链表节点
/// </summary>
public class StackNode
{
public string data { get; set; }//链表节点数据
public StackNode next { get; set; }//该链表节点的所指的栈底方向的相邻节点
/// <summary>
/// 初始化参数
/// </summary>
/// <param name="data">节点数据【string类型】</param>
public StackNode(string data)
{
this.data = data;
next = null;
}
}
//测试
class Program
{
static void Main(string[] args)
{
StackNode stackNode1 = new StackNode("1");
StackNode stackNode2 = new StackNode("2");
LinkStack linkStack = new LinkStack();
linkStack.Push(stackNode1);
linkStack.Push(stackNode2);
Console.WriteLine(linkStack.ShowStack());
Console.ReadKey();
}
}
}
转载于:https://my.oschina.net/mojiadan/blog/117660