토털이
토털이의 ios 개발 여정
토털이
hands-on 개발자 토털이입니다🌈
GitHub
전체 방문자
오늘
어제
  • 분류 전체보기 (7)
    • CS (2)
      • 자료구조&알고리즘 (2)
    • ios (1)
    • swift (2)
    • 🌈TIL (2)

블로그 메뉴

  • 홈
  • 태그
  • 글쓰기

공지사항

인기 글

태그

  • queue
  • AppBased
  • 앱실행과정
  • UIKit
  • 큐
  • AppLaunch
  • LinkedList
  • 링크드리스트
  • SWIFT

최근 댓글

최근 글

hELLO · Designed By 정상우.
토털이

토털이의 ios 개발 여정

CS/자료구조&알고리즘

[swift] 링크드 리스트로 큐 구현하기

2022. 9. 20. 23:12
  • 우선 기본적인 것들을 linked list로 구현해보자.
class Node {

    var value: String
    var next: Node?

    init(value: String, next: Node? = nil) {
        self.value = value
        self.next = next
    }
}

struct LinkedList {

    var head: Node?
    var tail: Node?

    init() {}

    var isEmpty: Bool {
        head == nil
    }

    mutating func push(_ value: String) {

        head = Node(value: value, next: head)
        if tail == nil {
            tail = head
        }
    }

    mutating func append(_ value: String) {

        guard !isEmpty else {
            push(value)
            return
        }

        tail?.next = Node(value: value)
        tail = tail?.next
    }

    mutating func pop() -> String? {

        let returnValue = head?.value
        head = head?.next
        if isEmpty {
            tail = nil
        }

        return returnValue
    }

    mutating func removeLast() -> String? {

        guard let head = head else {
            return nil
        }

        guard head.next != nil else {
            return pop()
        }

        var prev = head
        var current = head
        while let next = current.next {
            prev = current
            current = next
        }

        prev.next = nil
        tail = prev

        return current.value
    }

    mutating func removeAll() {
        head = nil
        tail = nil
    }
}
  • 이후 큐를 다음과 같이 만들어 주면 기본적인 큐가 완성된다.
class Queue {

    var queue: LinkedList = LinkedList()

    func enqueue(item: String) {
        queue.append(item)
    }

    func dequeue() -> String? {
        return queue.pop()
    }

    func removeAll() {
        queue.removeAll()
    }
}

'CS > 자료구조&알고리즘' 카테고리의 다른 글

[swift] 스택과 큐  (0) 2022.09.20
    'CS/자료구조&알고리즘' 카테고리의 다른 글
    • [swift] 스택과 큐
    토털이
    토털이
    ios를 공부하는 학생의 블로그입니다.

    티스토리툴바