https://www.acmicpc.net/problem/10828
using System;
using System.Collections.Generic;
using System.Text;
namespace boj
{
class Program
{
static void Main(string[] args)
{
var A = int.Parse(Console.ReadLine()); //첫째줄에는 명령의 수가 주어진다
Stack<int> stack = new(); //stack 객체 생성
StringBuilder sw = new(); //출력하기 위한 sw객체 생성 런타임 초과 방지
for (int i = 0; i < A; i++) //
{
string[] input = Console.ReadLine().Split(' ');
if(input[0] == "push")
{
stack.Push(int.Parse(input[1])); //push X: 정수 X를 스택에 넣는 연산이다.
}
else if(input[0] == "pop")
{
if (stack.Count == 0)
{
sw.AppendLine("-1"); //만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
}
else
{
sw.Append(stack.Pop() + "\n"); //pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다.
}
}
else if(input[0] == "size")
{
sw.Append(stack.Count + "\n"); //size: 스택에 들어있는 정수의 개수를 출력한다.
}
else if(input[0] == "empty") //empty
{
if (stack.Count == 0) //스택이 비어있으면 1
{
sw.AppendLine("1");
}
else
{
sw.AppendLine("0"); //아니면 0
}
}
else if(input[0] == "top")
{
if (stack.Count == 0) //스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
{
sw.AppendLine("-1");
}
else
{
sw.Append(stack.Peek() + "\n"); //top: 스택의 가장 위에 있는 정수를 출력한다. }
}
}
Console.WriteLine(sw.ToString()); //런타임 오버 방지용으로 만든 sw 출력
}
}
}
'C#' 카테고리의 다른 글
백준10845 c# (0) | 2025.04.14 |
---|---|
백준 9012 c# (0) | 2024.10.17 |
백준 9093 c# (3) | 2024.10.03 |