Data Structures

Stacks and Queues

Christopher Webb
Journey Of One Thousand Apps
2 min readJan 30, 2018

--

Stack

A stack is a Last In First Out data structure. Imagine an immense stack of bricks. You’ve been tasked with taking these bricks and placing them in boxes for shipping. So, looking at this vast stack, do we start pulling bricks from the bottom of the stack or do we take them off the top? Common sense would dictate that we start from the top, and not begin a 10,000 lb game of Jenga. That’s a lot like how stacks work here. The last element placed in the LIFO data structure is the first element that is retrieved from.

While a stack may superficially resemble an array, the ordering of the elements underpins the functionality. Therefore, when you create a stack, it is essential that you restrict how elements within it are accessed.

var stack = Stack<String>()stack.push(element: "one")print(stack.count) // 1stack.push(element: "two")print(stack.count) // 2stack.push(element: "three")print(stack.count) // 3stack.push(element: "four")print(stack.count) // 4stack.isEmpty() // Falseprint(stack.pop()) // Optional("four")print(stack.pop()) // Optional("three")print(stack.pop()) // Optional("two")print(stack.pop()) // Optional("one")

Queue

A queue is a First In First Out list data structure. A First In First Out data structure means elements can only be inserted in the back and dequeued at the front. A queue can best be represented in the real world by a line to purchase movies tickets. In a ticket line, the first person who gets in line gets to buy their tickets first, and everyone in the line buys their tickets in the order that they joined the line. Like with Stacks, the ordering of data removal from a queue is critical to it functioning correctly, so ensuring that access to the queue data is appropriately managed is vital.

var queue = Queue<String>()queue.isEmpty // truequeue.push(value: "one")print(queue.count) // 1queue.push(value: "two")print(queue.count) // 2queue.push(value: "three")print(queue.count) // 3queue.push(value: "four")print(queue.count) // 4queue.isEmpty // falseprint(queue.pop()) // oneprint(queue.pop()) // twoprint(queue.pop()) // threeprint(queue.pop()) // four

Practical Use For Stacks And Queues

Stacks and queues can be used as temporary data structures in situations where the order of a list needs to be preserved or the order in which items where added or removed is important.

--

--