-
Stack, Queue With SwiftDataStructure + Algorithm/Basic Theories 2021. 10. 12. 03:57
Stack 과 Queue 는, 아주아주 흔하게 볼 수 있는 DataStructure 입니다.
둘 사이 가장 다른 점은 데이터가 추가, 추출되는 순서겠지요.
Stack 의 경우, 가장 늦게 오는 데이터가 가장 일찍 나가고, (Last In, First Out, LIFO)
Stack 에서 사용하는 methods 로는 push(_:), pop() 이 있습니다.
Queue 의 경우, 가장 일찍 들어오는 데이터가 가장 일찍 나가는 구조입니다. (First In, First Out, FIFO)
Queue 에서 사용하는 methods 로는 enqueue(_:), dequeue() 가 있습니다.
Stack
Stack 은 말그래도 쌓아두는 구조입니다. 팬케이크를 생각하시면 편할 것 같아요.
Stack 에서 쓰이는 methods 로는 push, pop 이 있습니다.
push(_:) 는 가장 뒤쪽 데이터에 데이터를 추가, pop() 은 가장 뒤쪽 데이터를 return 하는 method 입니다.
struct Stack <Element> { var items: [Element] = [] mutating func push(_ item: Element) { items.append(item) } mutating func pop() -> Element { return items.removeLast() } }
가장 간단한 형태의 Stack 을 Generic Type 으로 만들어주었습니다. (생성할 때 Type 을 정해주시면 됩니다.)
처음에 Stack 을 만들 때 빈 array (items) 를 만들었고, struct 이기 때문에 각 method 의 앞에 'mutating' keyword 를 붙여주었어요.
push(_:) 를 호출하면 items 에 parameter 로 주어진 item 이 가장 뒤쪽에 추가되고,
pop() 을 호출하면 가장 뒤쪽에 있는 element 가 items array 에서 제거되는 동시에 그 element 가 return 됩니다.
pop() 은 Swift 에서 기본적으로 제공하는 .removeLast() 를 사용하였지만, 기본 로직은 다음과 같습니다.
1. items 의 마지막 element 를 (lastItem) 에 할당,
2. items 의 마지막 element 제거
3. return lastItem
// let lastItem = items[items.count - 1] // remove last item of items // return lastItem
아래는 잘 작동하는지 확인하기 위해 print statement 를 추가하여 작성한 코드와 결과입니다.
struct Stack <Element> { var items: [Element] = [] mutating func push(_ item: Element) { print("\(item) is about to be pushed, current items are \(items)") items.append(item) } mutating func pop() -> Element { print("removing last item from \(items)") return items.removeLast() } } var myStack = Stack<Int>() myStack.push(5) myStack.push(10) myStack.pop() myStack.pop() //5 is about to be pushed, current items are [] //10 is about to be pushed, current items are [5] //removing last item from [5, 10] //removing last item from [5]
아주아주 잘 작동하는 것을 확인할 수 있었습니다.
Queue
Queue 는 줄서는 구조를 생각하시면 좋을 것 같습니다. 영화관, 식당 등에서 줄을 설 때 가장 먼저 온 사람이 가장 먼저 들어가는 구조입니다. 사용되는 methods 로는 enqueue(_:), dequeue() 가 있으며, enqueue(_:) 는 가장 뒤쪽에 데이터를 추가, dequeue()는 가장 앞쪽에 있는 데이터를 제거하는 동시에 return 하는 methods 입니다.
struct Queue <Element> { var items: [Element] = [] mutating func enqueue(_ item: Element) { items.append(item) } mutating func dequeue() -> Element { return items.removeFirst() } }
위 Stack 과 아주 비슷하지요 ??
enqueue(_:) 와 push(_:) 는 기능이 같고, dequeue() 와 pop() 는 제거하는 array 의 위치만 다릅니다. (dequeue: 앞, pop: 뒤)
Swift 에서 Queue 를 관리하다보면, 'DispatchQueue' 라는 단어를 많이 접하게 됩니다.
주로 main Thread 또는 global Thread 로 원하는 작업을 넘길 때 사용되지요. 여기서의 Queue 도 위와 같은 구조입니다.
할 일들을 Queue(Thread) 로 Dispatch (보내다) 한다는 것은, 다음 작업 순서로 할 일을 줄세우는 것과 같습니다.
들어온 순서대로 처리를 해야하는게 당연하니까요.
(UI Update 는 반드시 MainThread 에서 해야합니다. 그 외 API call 등은 global (background thread) 에서 처리합니다. )
DispatchQueue.main.async {
// TODO in main thread
}
DispatchQueue.global().async {
// TODO in global thread
}
Dispatchqueue:
An object that manages the execution of tasks serially or concurrently on your app's main thread or on a background thread. ( from apple)
(설명: 할 일들을 어떻게 처리할지 관리하는 object (순서대로 or 동시에, main or background thread ))'DataStructure + Algorithm > Basic Theories' 카테고리의 다른 글
Dynamic Programming (with Fibonacci sequence(using Swift and Cache)) (0) 2021.10.19 LinkedList (0) 2021.10.13 Insertion Sort with Swift (0) 2021.10.09 SelectionSort with Swift (0) 2021.10.08 Bubble Sort With Swift (0) 2021.10.08