栈的顺序存储结构_C#实现2[ArrayList实现]

引用自: [Michael McMillan.Data Structures and Algorithms Using C#]

这里的实现是用ArrayList, 新数据项进栈的时候不需要担心调整表的大小. 我感觉这个实现比较清晰, 其中p_index直接指向栈顶元素.

using System;
using System.Collections;
namespace Stack
{
    class CStack
    {
        private int p_index;                 //栈顶
        private ArrayList list;  
        //属性
        public int Count                  
        {
            get { return list.Count; }
        }
        //构造器
        public CStack()
        {
            list = new ArrayList();
            p_index = -1;
        }

        public void Push(object item)         //进栈
        {
            list.Add(item);
            p_index++;
        }

        public object Pop()                   //出栈
        {
            object obj = list[p_index];
            list.RemoveAt(p_index);
            p_index--;
            return obj;
        }

        public void Clear()                   //清空栈
        {
            list.Clear();
            p_index = -1;
        }

        public object Peek()                  //返回栈顶元素
        {
            return list[p_index];
        }

    }
}

你可能感兴趣的:(ArrayList)