스택_10828번

[Python, Go] 백준 10828번 풀이

스택

  • 주어지는 명령에 따라 스택을 처리하는 문제이다. 파이썬은 큐나 스택을 지원하는 라이브러리가 있지만 사용하지 않고 리스트를 통해 구현했으며, Go는 슬라이스를 통해 구현했다.
  • 스택을 초기화할 필요가 있는 문제가 아니었으므로 하나의 파이썬의 경우 하나의 for문안에서 처리하고 Go는 각각의 명령에 따른 함수를 만들어 사용했다.

  • Python 풀이

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
import sys

n = int(sys.stdin.readline())

stack = []

# n = int(input())

for i in range(n):

order = sys.stdin.readline().rstrip()
# print(order)
if len(order.split()) == 2:
stack.insert(0,int(order.split()[1]))

else:
if order == "pop":
if stack == []:
print(-1)
else:
print(stack[0])
stack.pop(0)
elif order == "size":
print(len(stack))
elif order == "empty":
if stack == []:
print(1)
else:
print(0)
# top
else:
if not stack == []:
print(stack[0])
else:
print(-1)
  • Go를 통해 슬라이스를 다룰때 파이썬의 pop과 같은 내장함수가 없다.

    • 따라서, 슬라이스에서 하나를 제거할 때 슬라이스의 길이가 1인경우와 1이 아닌경우를 나눠서 생각했다.

    • 슬라이스의 길이가 1인경우, 남아있는 하나를 제거하고 empty slice를 만들기 위해 nil 처리

    • 슬라이스의 길이가 1이 아닌 경우, 슬라이스의 가장 끝의 하나를 제거하면 되므로 슬라이스의 길이 L 을 구하고 L-1 까지의 슬라이스만을 가져간다.

  • Go 풀이

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
78
79
80
81
82
83
84
85
package main

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)

var s []int

func s_push(x int) {
s = append(s, x)
}

func s_pop() {

if s == nil {
fmt.Printf("%d\n", -1)
} else if len(s) == 1 {
top := s[0]
fmt.Printf("%d\n", top)
s = nil
} else {
l := len(s)
top := s[l-1]
fmt.Printf("%d\n", top)
s = s[:l-1]
}
}

func s_size() {
l := len(s)
fmt.Printf("%d\n", l)
}

func s_empty() {
if s == nil {
fmt.Printf("%d\n", 1)
} else {
fmt.Printf("%d\n", 0)
}
}

func s_top() {
if s == nil {
fmt.Printf("%d\n", -1)
} else {
l := len(s)
top := s[l-1]
fmt.Printf("%d\n", top)
}
}

func main() {
var n int
inputReader := bufio.NewReader(os.Stdin)
fmt.Scanf("%d", &n)

for i := 0; i < n+1; i++ {
input, _ := inputReader.ReadString('\n')

order := strings.Split(input, " ")

action := strings.TrimSpace(order[0])

if len(order) == 2 {
n := strings.TrimSpace(order[1])
num, _ := strconv.Atoi(n)
s_push(num)
} else {
switch action {
case "pop":
s_pop()
case "size":
s_size()
case "empty":
s_empty()
case "top":
s_top()
}
}
}
}

Full Code

Full Code - Python

Full Code - Go

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×