[C#] ตัวแปร Stack

โค้ด

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        const int MAX_STACK = 12;
        Stack myStack = new Stack(MAX_STACK);

        private void btPush_Click(object sender, EventArgs e)
        {
            if (myStack.Count < MAX_STACK)
            {
                Random rnum = new Random();
                myStack.Push(rnum.Next(10));
                textBox1.Text = "";
                foreach (int i in myStack)
                {
                    textBox1.Text += i.ToString() + "\r\n";
                }
            }
            else
            {
                MessageBox.Show("Cannot Push - Full Stack");
            }
        }

        private void btPop_Click(object sender, EventArgs e)
        {
            if (myStack.Count > 0) 
            {

                int pnum = (int)myStack.Pop();
                MessageBox.Show("The Pop data is " + pnum.ToString());
                textBox1.Text = "";
                foreach (int i in myStack)
                {
                    textBox1.Text += i.ToString() + "\r\n";
                }
            }
            else
            {
                MessageBox.Show("Cannot Pop - Empty Stack");
            }
        }

        private void btPeek_Click(object sender, EventArgs e)
        {
            if (myStack.Count > 0)
            {
                MessageBox.Show("The top data is " + myStack.Peek().ToString());
            }
            else
            {
                MessageBox.Show("Cannot Peek - Empty Stack");
            }
        }

        private void btCount_Click(object sender, EventArgs e)
        {
            MessageBox.Show("The number of data is " + myStack.Count.ToString() + " from " + MAX_STACK.ToString());
        }

        private void btClear_Click(object sender, EventArgs e)
        {
            myStack.Clear();
            textBox1.Text = "";
        }

    }
}
Previous
Next Post »