개발자일걸요..?

10828번 스택 본문

알고리즘코딩/Baekjoon Online Judge

10828번 스택

Re_A 2021. 2. 22. 18:54
728x90
반응형

문제링크 : www.acmicpc.net/problem/10828

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net



버전 1. if문을 이용한 분기 ( 메모리 : 28776KB    시간 : 72ms)

import sys
N = int(sys.stdin.readline())
numbers = []
for _ in range(N):
    commend = sys.stdin.readline().split()
    if(commend[0] == "push"):
        num = int(commend[1])
        numbers.insert(0,num)
    elif(commend[0]=="pop"):
        if(len(numbers)==0):
            print(-1)
        else:
            print(numbers[0])
            del numbers[0]
    elif (commend[0] == "size"):
        print(len(numbers))
    elif (commend[0] == "empty"):
        if(len(numbers) ==0):
            print(1)
        else :
            print(0)
    elif(commend[0]=="top"):
        if (len(numbers) == 0):
            print(-1)
        else:
            print(numbers[0])

 

 

버전 2. 함수를 이용 ( 메모리 : 28776KB    시간 : 72ms)

numbers = []
def size():
    print(len(numbers))
def push(a):
    numbers.insert(0,a)
def pop():
    if(len(numbers)==0):
        print(-1)
    else:
        print(numbers[0])
        del numbers[0]
def empty():
    if(len(numbers)==0):
        print(1)
    else:
        print(0)
def top():
    if (len(numbers) == 0):
        print(-1)
    else:
        print(numbers[0])
        
import sys
N = int(sys.stdin.readline())
for _ in range(N):
    commend = sys.stdin.readline().split()
    if(commend[0] == "push"):
        push(commend[1])
    elif(commend[0] == "pop"):
        pop()
    elif (commend[0] == "size"):
        size()
    elif (commend[0] == "empty"):
        empty()
    elif (commend[0] == "top"):
        top()
반응형

'알고리즘코딩 > Baekjoon Online Judge' 카테고리의 다른 글

9012번 괄호  (0) 2021.02.22
10773번 제로  (0) 2021.02.22
1541번 잃어버린 괄호  (0) 2021.02.21
1931번 회의실 배정  (0) 2021.02.21
13305번 주유소  (0) 2021.02.20
Comments