了解集合本质必须要知晓的概念02-堆栈

在"了解集合本质必须要知晓的概念-链表"中,我们了解了链表的概念和种类,并且模拟了一个单向链表。本篇体验的堆栈是约束版的链表,只能在栈顶接收新节点和释放节点。

堆栈的主要操作是压栈和出栈。压栈是将新节点放在栈顶,出栈是从栈顶取出一个节点,返回新弹出节点的数据项。堆栈也称为后进先出的数据结构。

接着上一篇,写一个派生于List的类来模拟堆栈的压栈和出栈。

namespace LinkedListLibrary
{
    public class StackInheritance : List
    {
        public StackInheritance() : base("stack"){}
        public void Push(object dataValue)
        {
            InsertAtFront(dataValue);
        }
        public object Pop()
        {
            return RemoveFromFront();
        }
    }
}

客户端调用。

        public static void Main(string[] args)
        {
            StackInheritance stack = new StackInheritance();
            bool aBoolean = true;
            char aChar = 'a';
            int anInt = 12;
            string aStr = "hello";
            stack.Push(aBoolean);
            stack.Display();
            stack.Push(aChar);
            stack.Display();
            stack.Push(anInt);
            stack.Display();
            stack.Push(aStr);
            stack.Display();
            try
            {
                while (true)
                {
                    object removedObject = stack.Pop();
                    Console.WriteLine(removedObject + "被弹出~~");
                    stack.Display();
                }
            }
            catch (EmptyListException emptyListException)
            {                
                Console.Error.WriteLine(emptyListException.StackTrace);
            }
            Console.ReadKey();
        }

3 

参考资料:

Visual C# 2008大学教程--(第三版)

“了解集合本质必须要知晓的概念”系列包括:

了解集合本质必须要知晓的概念01-链表

了解集合本质必须要知晓的概念02-堆栈

了解集合本质必须要知晓的概念03-队列

了解集合本质必须要知晓的概念04-二叉查找树

原文地址:https://www.cnblogs.com/darrenji/p/3890483.html