![]() ![]() If you have any questions on queues in Swift, please join the forum discussion below! If you’re interested in more, check out the repo. ![]() This was just one of the many algorithms in the Swift Algorithm Club repository. You can also find alternative implementations and further discussion in the queue section of the Swift Algorithm Club repository. ![]() I hope you enjoyed this tutorial on making a queue! You can fix up your test code as follows:Īnd you can even try your Queue with different types as well: You’ve updated peek to return any type.You’ve updated dequeue to return any type.You’ve updated enqueue to take any type.Your goal is to allow the Queue to take in values of any type, so you’ll constrain your underlying LinkedList to be type T rather than a Int.You’ve changed the declaration of the Queue to take a generic type T.Public mutating func enqueue(_ element: Int) Add the following between the curly braces: You’ll use the LinkedList implementation included in the starter project to implement your queue. Note: Want to learn how the LinkedList works? Check out our Swift linked list tutorial, which walks you through it step by step. The playground also contains the code for a LinkedList (you can see this by going to View\Project Navigators\Show Project Navigator and opening Sources\LinkedList. The playground will contain an empty Queue: Start by downloading the queue starter project. In this section, you’ll implement a simple general-purpose queue that stores Int values. If the queue is empty, dequeuing would return nil. The next dequeue would return 57, and so on. This would return 10 because that was the first number you inserted. You could dequeue to pull the first element off the front of the queue: Then you could add the next number to the queue: The easiest way to understand a queue is to see how it’s used. It’s only fair! (A very similar data structure, the stack, is LIFO or last-in first-out.) The element you inserted first is also the first one to come out again. Often the order in which you add and remove these items matters.Ī queue gives you a FIFO or first-in, first-out order. Why would you need this? Well, in many algorithms you want to add items to a temporary list at some point and then pull them off this list again at a later time. This ensures that the first item you enqueue is also the first item you dequeue. Getting StartedĪ queue is a list where you can only insert new items at the back and remove items from the front. Note: New to the Swift Algorithm Club? Check out our getting started post first. ![]()
0 Comments
Leave a Reply. |