백준 10828번 스택 (C#)

김보근·2025년 7월 14일

백준

목록 보기
41/62

[백준 10828번] 스택 (C#)

오늘의 문제

스택 자료구조를 직접 구현하여 명령어에 따라 동작시키는 문제다.
명령어는 다음과 같다.

  • push X : X를 스택에 추가

  • pop : 스택에서 가장 위에 있는 수를 빼고 출력 (없으면 -1)

  • size : 스택에 들어있는 정수 개수 출력

  • empty : 스택이 비어있으면 1, 아니면 0 출력

  • top : 스택의 가장 위에 있는 수 출력 (없으면 -1)


https://www.acmicpc.net/problem/10828

내가 작성한 코드

using System;
using System.Collections.Generic;
using System.Text;

namespace backjoon
{
    internal class Program
    {
        static void Main()
        {
            int count = int.Parse(Console.ReadLine());
            Stack<int> stack = new Stack<int>();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                string[] input = Console.ReadLine().Split();

                switch (input[0])
                {
                    case "push":
                        stack.Push(int.Parse(input[1]));
                        break;

                    case "pop":
                        sb.AppendLine(stack.Count > 0 ? stack.Pop().ToString() : "-1");
                        break;

                    case "size":
                        sb.AppendLine(stack.Count.ToString());
                        break;

                    case "empty":
                        sb.AppendLine(stack.Count > 0 ? "0" : "1");
                        break;

                    case "top":
                        sb.AppendLine(stack.Count > 0 ? stack.Peek().ToString() : "-1");
                        break;
                }
            }

            Console.Write(sb.ToString());
        }
    }
}

깨달은 점

  • Console.WriteLine()를 매번 호출하면 시간초과가 발생한다.

  • StringBuilder로 출력할 문자열을 모아서 한 번에 Console.Write()로 출력해야 빠르게 처리된다.

  • switch문을 활용하면 if-else보다 코드가 더 깔끔해진다.

  • Stack.Count는 메서드가 아닌 프로퍼티라서 Count()가 아닌 Count로 사용한다

profile
게임개발자꿈나무

0개의 댓글