Created
June 20, 2021 06:42
-
-
Save Aditi3/befbbbb952d9b8b857111d3baff155af to your computer and use it in GitHub Desktop.
Implementing Queue Data Structure, FIFO
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
| import UIKit | |
| struct Queue<T> { | |
| var array: [T] = [] | |
| init() { } | |
| var isEmpty: Bool { | |
| return array.isEmpty | |
| } | |
| var peek: T? { | |
| return array.first | |
| } | |
| mutating func enqueue(_ element: T) -> Bool { | |
| array.append(element) | |
| return true | |
| } | |
| mutating func dequeue() -> T? { | |
| return isEmpty ? nil : array.removeFirst() | |
| } | |
| } | |
| extension Queue: CustomStringConvertible { | |
| var description: String { | |
| return String(describing: array) | |
| } | |
| } | |
| /// Create an Queue | |
| var queue = Queue<Int>() | |
| /// Add to the Queue | |
| queue.enqueue(10) | |
| queue.enqueue(20) | |
| queue.enqueue(30) | |
| queue.enqueue(40) | |
| queue.enqueue(50) | |
| print(queue) | |
| /// Remove from the Queue | |
| queue.dequeue() | |
| print(queue) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment