wwewbw

博客园 首页 新随笔 联系 订阅 管理

引用自: [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];
        }

    }
}

posted on 2010-02-09 14:18  wwewbw  阅读(543)  评论(0编辑  收藏  举报