Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# ใช้งาน Stack ด้วย Push และ Pop

ใช้งาน Stack ด้วยการเพิ่มสมาชิกผ่าน Push และนำออกผ่าน Pop

การเพิ่มสมาชิก (Push)

Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');

การนำออก (Pop)

st.Pop();
st.Pop();

ตัวอย่างเต็ม

using System;
using System.Collections;

namespace CollectionsApplication {
    class Program {
        static void Main(string[] args) {
            Stack st = new Stack();
            st.Push('A');
            st.Push('M');
            st.Push('G');
            st.Push('W');
            
            Console.WriteLine("Current stack: ");
            foreach (char c in st) {
                Console.Write(c + " ");
            }
            Console.WriteLine();
            
            st.Push('V');
            st.Push('H');
            Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
            
            Console.WriteLine("Current stack: ");
            foreach (char c in st) {
                Console.Write(c + " ");
            }
            Console.WriteLine();
            
            Console.WriteLine("Removing values ");
            st.Pop();
            st.Pop();
            st.Pop();
            
            Console.WriteLine("Current stack: ");
            foreach (char c in st) {
                Console.Write(c + " ");
            }
        }
    }
}

ผลลัพธ์

Current stack: W G M A
The next poppable value in stack: H
Current stack: H V W G M A
Removing values
Current stack: G M A