Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 10828๋ฒˆ - ์Šคํƒ(stack)

๊ฐ์ž ๐Ÿฅ” 2022. 1. 16. 15:59
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ๋งํฌ

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

๋ฐ˜์‘ํ˜•
 

10828๋ฒˆ: ์Šคํƒ

์ฒซ์งธ ์ค„์— ์ฃผ์–ด์ง€๋Š” ๋ช…๋ น์˜ ์ˆ˜ N (1 ≤ N ≤ 10,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ๋ช…๋ น์ด ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ์ •์ˆ˜๋Š” 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 100,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. ๋ฌธ์ œ์— ๋‚˜์™€์žˆ์ง€

www.acmicpc.net

 
 
 

๋‚ด๊ฐ€ ํ‘ผ ํ’€์ด

์ผ๋ฐ˜์ ์ธ ์Šคํƒ์˜ ๊ฐœ๋…์„ ํ™•์ธํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ํ•จ์ˆ˜๋กœ ๊ฐ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•˜์˜€๊ณ , switch case๋ฌธ์„ ํ™œ์šฉํ•˜์˜€๋‹ค.

var stack:[Int] = []
let n = Int(readLine()!)!

for _ in 1...n{
    let a = readLine()!.split(separator:" ").map{String($0)}
    switch a[0] {
        case "push":
            push(Int(a[1])!)
        case "pop":
            print(pop())
            break
        case "size":
            print(size())
            break
        case "empty":
            print(empty())
            break
        case "top":
            print(top())
            break
        default:
            break
    }
    
}


func push(_ x:Int){
    stack.append(x)
}

func pop() -> Int{
    if let popValue = stack.popLast() {
        return popValue
    } else {
        return -1
    }
}

func size() -> Int{
    return stack.count
}

func empty() -> Int{
    if stack.isEmpty {
        return 1
    }else{
        return 0
    }
}

func top() -> Int{
    if let last = stack.last {
        return last
    }else{
        return -1
    }
}

 

๋ฐ˜์‘ํ˜•