Created
September 5, 2023 04:52
-
-
Save WhiteHyun/16a37bf465a71a5df591a2f471256918 to your computer and use it in GitHub Desktop.
Swift Queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Queue<Element> { | |
private var frontArray: [Element] = [] | |
private var backArray: [Element] = [] | |
mutating func append(_ element: Element) { | |
backArray.append(element) | |
} | |
mutating func popFirst() -> Element? { | |
if !frontArray.isEmpty { return frontArray.popLast() } | |
frontArray = backArray.reversed() | |
backArray = [] | |
return frontArray.popLast() | |
} | |
} | |
extension Queue: Collection { | |
typealias Element = Element | |
var startIndex: Int { | |
0 | |
} | |
var endIndex: Int { | |
frontArray.count + backArray.count | |
} | |
subscript(position: Int) -> Element { | |
precondition(startIndex..<endIndex ~= position, "Index out of bounds") | |
if position < frontArray.count { | |
return frontArray[frontArray.count - position - 1] | |
} | |
return backArray[position - frontArray.count] | |
} | |
func index(after i: Int) -> Int { | |
precondition(i < endIndex, "Can't advance beyond endIndex") | |
return i + 1 | |
} | |
} | |
extension Queue: ExpressibleByArrayLiteral { | |
init(arrayLiteral elements: Element...) { | |
backArray = elements | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment