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---------------"
}
}
'๐ฑ๐ iOS > Code Templates' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] Queue ํ ๊ตฌํํ๊ธฐ (๋ฐฐ์ด / ์ฐ๊ฒฐ๋ฆฌ์คํธ / Two Stack / Head ๋ฐฉ์) (0) | 2022.12.21 |
---|---|
[Swift] Linked List - Singly Linked List ๊ตฌํ (0) | 2022.12.15 |
[Swift] URL์์ ๋น๋๊ธฐ๋ก ์ด๋ฏธ์ง ๋ค์ด๋ก๋ ๋ฐ ์บ์ฑํ๊ธฐ - NSCache (0) | 2022.05.18 |
์ฝ๋๋ก UIView ๋ง๋ค๊ธฐ ๊ธฐ๋ณธ ํ ํ๋ฆฟ (0) | 2022.05.11 |
UIFont Extension - custom font (0) | 2022.05.11 |