上一篇我们通过数组结构实现了栈结构(准确的说是栈的顺序存储结构),现在我们通过链(单链)存储栈,也就是链栈。
通常对于正向单链表来说,是从头节点开始,在链的尾部附加节点,前一个节点的指针指向附加节点;对于实现栈结构来说是在栈顶(链尾部)插入节点,指针指向上一个节点,所以实现栈结构的链可以说是反向单链表。
public class LinkStackNode<T> { /// <summary> /// 数据存储 /// </summary> public T data { get; set; } /// <summary> /// 节点指针 /// </summary> public LinkStackNode<T> next { get; set; } public LinkStackNode(T d) { data = d; } }
/// <summary> /// 链栈 /// </summary> public class LinkStack<T> { //对于栈来说,不需要又链的头节点,所以此处我们忽略 /// <summary> /// 栈顶 /// </summary> public LinkStackNode<T> top { get; set; } /// <summary> /// 总长度 /// </summary> public int count { get; set; } /// <summary> /// 入栈 /// </summary> /// <param name="data"></param> public void push(T data) { LinkStackNode<T> linkedListNode = new LinkStackNode<T>(data); linkedListNode.next = top; top = linkedListNode; count++; } /// <summary> /// 取栈顶节点,但不删除该节点 /// </summary> /// <returns></returns> public LinkStackNode<T> Peek() { if(count == 0) throw new InvalidOperationException("空栈"); return top; } /// <summary> /// 出栈 /// </summary> /// <returns></returns> public LinkStackNode<T> Pop() { if (count == 0) throw new InvalidOperationException("空栈"); LinkStackNode<T> tp = top; top = top.next; count--; return tp; } /// <summary> /// 打印链栈所有元素 /// </summary> public void showAll() { var node = top; for (int i = 0; i < count; i++) { Console.WriteLine($"{i},data:{node.data}"); node = node.next; } } }
测试:
LinkStack<string> link = new LinkStack<string>(); link.push("第一"); link.push("第二"); link.push("第三"); link.showAll(); Console.WriteLine(); Console.WriteLine($"Peek:{link.Peek().data}"); Console.WriteLine(); link.push("第四"); link.push("第五"); Console.WriteLine(); link.showAll(); link.Pop(); Console.WriteLine(); link.showAll();