Last active
March 27, 2017 20:03
-
-
Save BrandonShega/fca4c5c8b5649bade4d272a48c8fc934 to your computer and use it in GitHub Desktop.
Queue with two stacks
This file contains hidden or 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
var queue = Queue<String>() | |
queue.enqueue("Hello") | |
queue.enqueue("World") | |
queue.dequeue() // "Hello" | |
queue.dequeue() // "World" | |
queue.dequeue() // nil |
This file contains hidden or 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<T> { | |
var stack1 = Stack<T>() | |
var stack2 = Stack<T>() | |
mutating func enqueue(_ element: T) { | |
stack1.push(element) | |
} | |
mutating func dequeue() -> T? { | |
moveElements() | |
return stack2.pop() | |
} | |
var isEmpty: Bool { | |
return stack1.isEmpty && stack2.isEmpty | |
} | |
mutating func peek() -> T? { | |
moveElements() | |
return stack2.peek() | |
} | |
private mutating func moveElements() { | |
guard stack2.isEmpty else { return } | |
while let element = stack1.pop() { | |
stack2.push(element) | |
} | |
} | |
} |
This file contains hidden or 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 Stack<T> { | |
var elements: [T] = [] | |
mutating func push(_ element: T) { | |
elements.append(element) | |
} | |
mutating func pop() -> T? { | |
return elements.popLast() | |
} | |
func peek() -> T? { | |
return elements.last | |
} | |
func isEmpty: Bool { | |
return elements.count == 0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment