2024-04-01 22:50:19

 

스택을 직접 구현하여, 스택의 메서드들을 만들어 보는 문제이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
 
namespace 연습장
{
    internal class Program
    {
        static List<int> stack = new List<int>();
        static StringBuilder sb = new StringBuilder();
        static void Main(string[] args)
        {
            using var reader = new StreamReader(Console.OpenStandardInput());
            using var print = new StreamWriter(Console.OpenStandardOutput());
 
 
            int N = int.Parse(reader.ReadLine());
 
            for (int i = 0; i < N; i++)
            {
                int select = -1;
                int num = -1;
                int[] menu = Array.ConvertAll(reader.ReadLine().Split(), int.Parse);
                if (menu[0== 1)
                    add_data(menu[1]);
                else if (menu[0== 2)
                    add_pop();
                else if (menu[0== 3)
                    count_stack();
                else if (menu[0== 4)
                    is_clear();
                else
                    print_top();
            }
            print.WriteLine(sb);
 
        }
 
        static void add_data(int num)
        {
            stack.Add(num);
        }
 
        static void add_pop()
        {
            if (stack.Count == 0)
            {
                sb.Append("-1" + "\n");
                return;
            }
            sb.Append(stack[stack.Count - 1+ "\n");
            stack.RemoveAt(stack.Count - 1);
        }
        static void count_stack()
        {
            sb.Append(stack.Count + "\n");
        }
        static void is_clear()
        {
            if (stack.Count == 0)
                sb.Append(1 + "\n");
            else
                sb.Append(0 + "\n");
        }
        static void print_top()
        {
            if (stack.Count == 0)
            {
                sb.Append(-1 + "\n");
                return;
            }
            sb.Append(stack[stack.Count - 1+ "\n");
        }
    }
}
cs

 

크기가 가변적인 List를 이용해 스택을 구현 해 주었다.

솔직히 구현은 하기는 했는데, 뭔가 메서드 들을 왕창 갖다 써서 좀 그런 거 같다.

나중에 스택을 배우게 되면(한 7~8주차 쯤?) 메서드 보다는 직접 명령문들을 이용해서 구현해 보고 싶다