본문 바로가기

 𝗔𝗣𝗣𝗟𝗘/SWIFT : GRAMMAR

Swift 기초 문법 - Stack(스택) & Queue(큐)

 

 

 

 

Stack(스택) & Queue(큐)

 

 

💡 Stack(스택) & Queue(큐)

 

 

Stack(스택)

 

- 후입선출(LIFO, Last-In-First-Out) 구조를 가지고 있다.

  가장 마지막에 추가된 요소가 가장 먼저 제거 됨

- Swift에서는 따로 Stack을 지원하지는 않으나, Array를 사용하여 Stack을 구현할 수 있다.

  append() 메서드로 요소를 스택의 맨 끝에 추가하고, popLast() 메서드로 마지막 요소를 제거할 수 있음

- 주요 연산: push(삽입)과 pop(삭제)

    push : 스택의 최상위에 구성요소 추가

    pop : 스택의 최상위의 구성요소 제거

 

/*
<T> 에 대해서는 추후 배울 예정
제네릭이라는 것인데, 하나의 타입으로 국한되지 않고
타입에 유연하게 코드를 작성할 수 있는 기능입니다.
*/

struct Stack<T> {
    private var stack: [T] = []
    
    public var count: Int {
        return stack.count
    }
    
    public var isEmpty: Bool {
        return stack.isEmpty
    }
    
    public mutating func push(_ element: T) {
        stack.append(element)
    }
    
    public mutating func pop() -> T? {
        return isEmpty ? nil : stack.popLast()
    }
}

var stack = Stack<Int>()
stack.push(10)
stack.push(20)
stack.pop() // 20

 

 

Queue(큐)

 

- 선입선출(FIFO, First-In-First-Out) 구조를 가지고 있다.

    가장 먼저 추가된 요소가 가장 먼저 제거 됨

- Swift에서는 따로 Queue를 지원하지는 않으나, Array를 사용하여 Queue를 구현할 수 있다.

- 주요 연산: enqueue(삽입)와 dequeue(삭제)

   enqueue(_:) : 메서드로 요소를 큐에 추가

    dequeue() : 메서드로 큐에서 요소를 제거하고 반환

 

// Array 로 구현한 Queue
struct ArrayQueue<T> {
    // 빈 Array 선언
    private var queue: [T] = []

    // Queue 내 원소 개수
    public var count: Int {
        return queue.count
    }

    // Queue 가 비었는지
    public var isEmpty: Bool {
        return queue.isEmpty
    }

    // 삽입 메소드
    public mutating func enqueue(_ element: T) {
        queue.append(element)
    }

    // 삭제 메소드
    public mutating func dequeue() -> T? {
        return isEmpty ? nil : queue.removeFirst()
    }

    // Queue 전체 삭제
    public mutating func clear() {
        queue.removeAll()
    }
}

 

 

 

Recent Posts
Visits
Today
Yesterday
Archives
Calendar
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31