上次我们学了顺序栈,这次我们接触一下链式堆栈
栈的链式存储实现
栈的链式存储结构实际上就是一个单链表,叫做链栈。插入和删除操作只能在链栈的栈顶进行
先是自定义链栈的结点
class LinkStackNode<T>
{
private LinkStackNode<T> next;//定义下一个节点的地址
private T values;//存储数据
public T Value
{
get { return values; }
set { values = value;}
}
public LinkStackNode<T> Next
{
get { return next; }
set { next = value; }
}
public LinkStackNode()
{
next = null;
values = default(T);
}
public LinkStackNode(T data)
{
values = data;
next = null;
}
}
再自定义链栈
class LinkStack<T>
{
private LinkStackNode<T> top;//定义一个头结点
private int count;//堆栈元素个数
public int Count
{
get { return count; }
set { count = value; }
}
public LinkStack()
{
top = new LinkStackNode<T>();
count = 0;
}
public bool IsEmpty()
{
return top.Next == null && count ==0;
}
public void Push(T data)
{
LinkStackNode<T> newdata = new LinkStackNode<T>(data);
if (newdata == null)
{
return;
}
newdata.Next = top.Next;
top.Next = newdata;
count++;
}
public T Pop()
{
LinkStackNode<T> currentdata = top.Next;
if (IsEmpty())
{
Console.WriteLine("栈为空,出栈失败!");
return default(T);
}
top.Next = currentdata.Next;
count--;
return currentdata.Value;
}
public T Peek()
{
LinkStackNode<T> currentdata = top.Next;
if (IsEmpty())
{
Console.WriteLine("栈为空,访问栈失败!");
return default(T);
}
return currentdata.Value;
}
public void Clear()
{
top.Next = null;
count--;
}
}
再验证一下
//链栈
LinkStack<int> a = new LinkStack<int>();
Console.WriteLine("-------------------进行入栈--------------------");
for (int i = 0; i < 5; i++)
{
a.Push(i);
}
Console.WriteLine("当前元素个数为"+a.Count);
Console.WriteLine("-------------------入栈完成--------------------");
Console.WriteLine("-------------------进行出栈--------------------");
for (int i = 0; i < 5; i++)
{
Console.WriteLine("当前栈顶为" + a.Peek());
a.Pop();
}
Console.WriteLine("-------------------出栈完成--------------------");
Console.WriteLine("当前元素个数为" + a.Count);
Console.ReadKey();
看看结果
好的 今天链栈学习就到此结束