본문 바로가기

자료구조

스택 연습문제 (문자열 뒤집기)

using System;
using System.Collections;

namespace HelloWorld
{
    class App
    {
        public App()
        {
            //문자열을 배열에 옮김
            string str = "안녕하세요";
            string[] arr = new string[str.Length];
            for (int i = 0; i < str.Length; i++)
            {
                string w = str[i].ToString();
                arr[i] = w;
            }
            //배열의 요소를 출력
            foreach ( string w in arr)
            {
                Console.WriteLine(w);
            }
            Console.WriteLine();
            //선언하고 초기화부터
            Stack stack = new Stack();

            //스택에 넣는다
            for (int i = 0; i < str.Length; i++)
            {
                stack.Push(arr[i]);
            }
            Console.WriteLine();
            Console.WriteLine("stack count: {0}", stack.Count);
            Console.WriteLine();
            object[] arr2 = new string[stack.Count];
            //배열에 넣는다
            for (int i = 0; i < str.Length; i++)
            {
                object popStack = stack.Pop();
                arr2[i] = popStack;
            }

            //출력한다
            Console.Write("뒤집기결과 : ");
            foreach (object obj in arr2)
            {
                Console.Write("{0}", obj);
            }
            Console.WriteLine();
        }
    }
}