Bibi's DevLog ๐Ÿค“๐ŸŽ

[Swift] Stack ์Šคํƒ ๊ตฌํ˜„ (๋ฐฐ์—ด / ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•˜๊ธฐ) ๋ณธ๋ฌธ

๐Ÿ“ฑ๐ŸŽ iOS/Code Templates

[Swift] Stack ์Šคํƒ ๊ตฌํ˜„ (๋ฐฐ์—ด / ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•˜๊ธฐ)

๋น„๋น„ bibi 2022. 12. 20. 15:31

๋ฐฐ์—ด๋กœ ๊ตฌํ˜„ํ•œ Swift์˜ Stack


struct Stack<Element> {
    fileprivate var array: [Element] = []

    var isEmpty: Bool {
        return array.isEmpty
    }

    var count: Int {
        return array.count
    }

    mutating func push(_ element: Element) {
        array.append(element)
    }

    mutating func pop() -> Element? {
        return array.popLast()
    }

    func peek() -> Element? {
        return array.last
    }
}


extension Stack: CustomStringConvertible {
    var description: String {
        let topDivider = "---Stack---\n"
        let bottomDivider = "\n-----------\n"

        let stackElements = array.map { "\($0)" }.reversed().joined(separator: "\n")
        return topDivider + stackElements + bottomDivider
    }
}

์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•œ Swift์˜ Stack

class Node<T> {

    let value: T
    var next: Node?

    init(value: T) {
        self.value = value
    }
}

class Stack<T> {

    var top: Node<T>?

    func push(_ value: T) {
        let currentTop = top
        top = Node(value: value)
        top?.next = currentTop
    }

    @discardableResult
    func pop() -> T? {
        let currentTop = top
        top = top?.next
        return currentTop?.value
    }

    func peek() -> T? {
        return top?.value
    }
}

extension Node: CustomStringConvertible {
    var description: String {
        guard let next = next else { return "\(value)" }
        return "\(value)\n" + String(describing: next)
    }
}

extension Stack: CustomStringConvertible {
    var description: String {
        guard let top = top else { return "---- Stack is EMPTY ----" }
        return "---- Stack ----\n" + String(describing: top) + "\n---------------"
    }
}