数据结构与算法学习笔记(C#)

004_自己实现栈Stack

2017-05-15  本文已影响3人  HMY轩园
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;//

namespace CStack
{
    class Program
    {
        private ArrayList list;//集合
        private int p_Index;//索引标志

        /// <summary>
        /// 构造器
        /// </summary>
        public Program() {
            list = new ArrayList();
            p_Index = -1;//没放数据前
        }
        /// <summary>
        /// 获取元素个数
        /// </summary>
        public int count {
            get { return list.Count; }
        }
        /// <summary>
        /// 增加 入栈
        /// </summary>
        /// <param name="item"></param>
        public void push(object item) {
            list.Add(item);//自动放到末尾
            p_Index++;//索引自加
        }
        /// <summary>
        /// 提取
        /// </summary>
        /// <returns></returns>
        public object pop() {
            object obj = list[p_Index];//出栈
            list.RemoveAt(p_Index);//删除
            p_Index--;//
            return obj;
        }
        /// <summary>
        /// 清空
        /// </summary>
        public void clear() {
            list.Clear();
            p_Index = -1;
        }
        /// <summary>
        /// 最后一个元素
        /// </summary>
        /// <returns></returns>
        public object peek() {
            return list[p_Index];
        }

        static void Main(string[] args)
        {
            Stack myStack = new Stack(30);
            //Stack<string> myStack = new Stack<string>(30);
          


            Program alist = new Program();//实例化一个栈

            string ch;
            string word = "awwa34";
            bool ispalindrome = true;//是否为回文

            for (int i = 0; i < word.Length; i++)
            {
                alist.push(word.Substring(i,1));//入栈
            }


            int pos = 0;
            while (alist.count>0)
            {
                ch = alist.pop().ToString();//栈最后一个
                if (ch!=word.Substring(pos,1))//word.Substring(pos,1)取word的指定索引开始一个字符
                {
                    ispalindrome = false;
                    break;
                }
                pos++;
            }
            if (ispalindrome)
            {
                Console.WriteLine("是回文");
            }
            else
            {
                Console.WriteLine("不是回文");
            }

            Console.Read();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读