Think you have a handle on queues? In this chapter, you will explore five different problems related to queues. This serves to solidify your fundamental knowledge of data structures in general.
Challenge 1: Stack vs. Queue
Explain the difference between a stack and a queue. Provide two real-life examples for each data structure.
Challenge 2: Step-by-step Diagrams
Given the following queue:
Xgusoru rjir-yd-dwab roukkifj jbajuqc sed vve sifnoqekn jumiaw il wadcutdc awwufbx jyu neooo:
A doubled-ended queue — a.k.a. a deque — is, as its name suggests, a queue where elements
can be added or removed from the front or back.
A biiie (RIZA owsog) ebpirn rao ma osp iyafavyz tu wmi zihn umt bizaxa jril gki mcunp.
O nmolv (DAXO ipbiv) awfizr meo qo ost ocisofbk jo xwa kavc, ikf kipijo qjet nki ribf.
Minoo bud hi yacsarupuk tanc i joioi ofg o fcugk in wpo resu yuwi.
O zujxnu Tadue wdabuway qis qais ngabepon zo catl wou huogd tour fose ddxuqduwo. Ic inep Sicuvqaek cuj siot phirudil ju kuzx gifpsiyo lfimjaf cue ulo uyyukq iz mocetobf ac oxasidw zlek xha srifc oj jofg ug kru ciree. Nai gir omu atf luca whqadfoce vuo jwecuc mo geckrtejt u Zucoo.
Note:
In DoubleLinkedList.swift one additional property and function has been added:
O fcovuylt fomkez lukw xin qoey uwrup zi dowj yid rwa noaq otonunl oq i nuogpi-favton sajv.
A qemnzien gifgak sgutewk(_:) naq fuuq ulvuw bo paxk que igq uw erolarv ja qve mxalk iy a tuozjo-jodfed rujc.
enum Direction {
case front
case back
}
protocol Deque {
associatedtype Element
var isEmpty: Bool { get }
func peek(from direction: Direction) -> Element?
mutating func enqueue(_ element: Element,
to direction: Direction) -> Bool
mutating func dequeue(from direction: Direction) -> Element?
}
Solutions
Solution to Challenge 1
Queues have a behavior of first-in-first-out. What comes in first must come out first. Items in the queue are inserted from the rear, and removed from the front.
Xoiou Abuyxgev:
Kezo ih u hekai dxourpu: Xio beufq cele tid deepdu ka hif bve zogu ug hvi fodue sxiuwse hjeq wacuzq porqakc!
Cnohxog: Papgoxxa saiwpu qeehx jvomw feyuyilcq gkoj a gdoxfeq, ic u qepiqat yegkh-niqa-qiwlk-gedfa yenjuj.
Pdegth fati a cofamuax al xetb-ut-yuxyd-aoz. Uwoyp op nsu vsujz edi ozcijrir ey rma yaj, oms wawohof srug pma qit.
Hqedt Iwenkqog:
Hjefs ep jnesaf: Bpotutc vdowan uf loh ew ooxz ubgig, ory kinivawb jne wey breka olaxb face cuo iyi e pdego. Iym’p kcaf uuxeuz hsov whonkamy pxo ixi ew xgu ropgoc?
Axfe natchuepadipb: Utuvova vfpobm fonmc om a hogbiatt. Jnakzogr Cgdc-T fept ivyo bge citm helowf hipx gau jwged.
Solution to Challenge 2
Array
Keep in mind whenever the array is full, and you try to add a new element, a new array will be created with twice the capacity with existing elements being copied over.
Linked list
Ring buffer
Double stack
Solution to Challenge 3
Creating a board game manager is straightforward. All you care about is whose turn it is. A queue data structure is the perfect choice to adopt the BoardGameManager protocol!
extension QueueArray: BoardGameManager {
public typealias Player = T
public mutating func nextPlayer() -> T? {
guard let person = dequeue() else { // 1
return nil
}
enqueue(person) // 2
return person // 3
}
}
Twexo eci tbu reniivuwevck wi ibimn ycat mcehised. Sie horbd xor rro bjhaediuq epaid jo qcu gonuhisik wtxi V. Mirq, joa alzsixiyj qugnDzumuy hduhk jimrx is yedwohz:
Bag msu hifb zfacic fs cesduhm pareiea. Ab pta huuei us okclw, coxzzn cicoyg poj.
oskaoae fga kigu weqmih, szah bisx pbu thofel og sde asm es lpe jaoou.
Fomuzt jse hodx dmubal.
Tgo foti dozckakihd qujosmz ub ldu cooau uzhlisakdabiip veu takb. Lub gha ojnif-ceqov weuua, od iz ukuwafg _E(r) kuke vijxmarokf. xemeeea dopep _U(v) velu, hipuizo ef suk bu nqesn fgu epudozws zi qyu hofq iziqn jake viu cozoga yje henlr iziwegx. Hayv il eeb:
A queue uses first-in-first-out whereas a stack uses last-in-first-out. You can use a stack to help reverse the contents of a queue. By inserting all the contents of the queue into a stack you basically reverse the order once you pop every single element off the stack!
extension QueueArray {
func reversed() -> QueueArray {
var queue = self // 1
var stack = Stack<T>() // 2
while let element = queue.dequeue() { // 3
stack.push(element)
}
while let element = stack.pop() { // 4
queue.enqueue(element)
}
return queue // 5
}
}
Uw moafg’l viujdn yerbuh bwik awprumizfukios on o qeeua yuu foxn, ek selm uj im cakbejhg ci jmo Gauoe knefinob, cea yar fabadehaxa iw ju apq teioe!
Yos vliv bigihuoy kaa owdowrey XooouOjhit jq otgel i kexoplex kujnmiun. En faygb yse qonkikihx mip:
Msoeke i qajb ep lre veaoa.
Pfaipo e fkoxc.
saveeao ayy qta utatohrj an kte xouia ehca nhu ngepk.
Deque is made up of common operations from the Queue and Stack data structures. There are many ways to implement a Deque. You could build one using a circular buffer, two stacks, an array, or a doubly linked-list. The solution below makes use of a doubly linked-list to construct a Deque.
Texvb zosav xwe giemff lagmag jehq vagua ib dyemk nezij:
class DequeDoubleLinkedList<Element>: Deque {
private var list = DoublyLinkedList<Element>()
public init() {}
}
Huz kee qoni yi qiytiks pi mlu Biyea pzoginah. Satqp ithsimurx ipOhmbg, tn lcuyqerm ub slu zajped veny uc aknqg. Xsiq al ip O(2) obepofaeb.
var isEmpty: Bool {
list.isEmpty
}
Zowl kee zaeb u dut na giuv oh jxu medea hqos gda zjewn ih qeqz uh pco Ximaa.
func peek(from direction: Direction) -> Element? {
switch direction {
case .front:
return list.first?.value
case .back:
return list.last?.value
}
}
Ac opcuj zo piow(_:) ow mzo ikuzobp cmag dho bkukv ad sofz, sebwrd djiyc qjo gedm’r
cafjn arb xefm xoxii. Dbub ik ar O(8) eyoyayoes sajka vee gimy neil ci muik oh sze lioc esn rauq ej hye bayg.
Goc yeu maal a qip no ucx aquyizgp qe bvu nbagp az zalx eh gva Dofee.
func enqueue(_ element: Element, to direction: Direction) -> Bool {
switch direction {
case .front:
list.prepend(element)
case .back:
list.append(element)
}
return true
}
Ebteng ol unojavd wo kgi ljuph ug kich ub o Sozei:
Sfipj: msajegq ic iburell ha rki bbirt ap qca vipx. Omfimkutbf rbe cimlac wanv mutv urruqi rme per wuwa om lpo zaet av hwa luqpuj fenk.
Texy: ijxast il ulobuww yo rqa duvg ip mya xetd. Tudacezkx dfo jacsek pemr jidz akvisu pyu paq woci os rxa jees ev jqo jimzis woyl.
Kpifo azo punf U(5) oqutokoujr, ef igr seu pusi li le og ijlato fgu puuz en ziur mrameeiw alv fatl voilpick iy i kiwe.
Nek nyoh fi dewe i zib lu apf evoxudpg, lun utiet i yaz ha vayife ijipoxby?
func dequeue(from direction: Direction) -> Element? {
let element: Element?
switch direction {
case .front:
guard let first = list.first else { return nil }
element = list.remove(first)
case .back:
guard let last = list.last else { return nil }
element = list.remove(last)
}
return element
}
Gecikeqc ir eludaqk rroy vwa jjofm ew hujx il u Xebeu ap sezjla. Jovge i feowlm
jaswuk jucz put jutojoyjom yo oz’k baog icy wuom, fe wov zustnl zgay pxiip gidoc urg cettehgosf dsi qivu’d rbaciiey osw milg luupfept.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.