Building Stack & Queue Algorithms with Swift

Wayne Bishop
Swift Algorithms & Data Structures
4 min readDec 14, 2018

--

Stacks and queues are structures that help organize data in a particular order. Their concept is based on the idea that information can be organized similarly to how things interact in the real world. For example, a stack of dinner plates can be represented by placing a single plate on a group of existing plates. Similarly, a queue can be easily understood by observing groups of people waiting in a line at a concert or grand opening.

These structures can be implemented in various ways. Any app that makes use of a shopping cart, waiting list or playlist makes use of a stack or queue. In software development, a call stack is often used as an essential debugging / analytics tool. For this essay, we’ll discuss and implement a stack and queue data structures in Swift.

HOW QUEUES WORK

Queues are based on the concept of “first-in, first-out”. As new elements are created, they are added to the back of the queue. Items are preserved in order until requested. When a new element is requested, the top level item is removed and is sent to the receiver:

Similar to a linked list, we’ll create a generic Node class to manage stack and queue items:

//generic node structureclass Node<T> {

var key: T?
var next: Node?
}

--

--