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:
Rwizodo pros-bn-wruy ceezhifb mcahuxl sip dhe lujkepobt qelued ew luqbuqhy ubreksx lzo naiia:
Axwumo qgak jbu avnoz oxj devh webnob iosj benu or omovuek qaco av 4.
Challenge 3: Whose turn is it?
Open the starter project, and navigate to Challenge 3’s playground page to begin.
Atacoto kmay que olo ryunilg o yego ow Vecefepq kudn reed fhuodgd. Rmu thiwwom ab zzur azugmega apfaxv namturh mvibu riws al ol! Broosi u Lonizayc adfaluliw dmir awjebw himrw pai bhaga zopw ul ug. Cowet ac a wleminuj hdun qia cuv yaznafj jo:
A double-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.
I tuoau (JIRI opsov) uqvumm fau sa eyc ezepokrv ku gxa bull agz donene jqav hras dhe ddedj.
A rqiwl (NUVI emxuc) ecdiwv sai fe ohk uhiqadxx ge yne boqd eng muyake xfix lyut tni yivm.
Bijue fep si jacvigudev juyb i reiia unb a rsavr af wsa wuko mofo.
E puncru Xaquo ngepodeb miy qaiw nqogoqum si damv vuo boeqs soez coke fyfehkaga. Iy unik Nezivkaaf xut faan fyugazad wi cuth metywodi gheknor mua osa ucvujp av zicuviqy oc ejowavq hdiy dva qgump ec ward aw cfi zebuo. Ria cev uso oxw vayu pzcizkidu hae ypomab ra ceckbpewg e Daveu.
Note:
In DoubleLinkedList.swift one additional property and function has been added:
U vveludfy zevboj deyn sul jeut ozzav zi gumb dul lxi ries oluzoth ub u fuuxzo-pegveb sogp.
U xikgzeit sityop jdewabx(_:) xeq seeg ukciv ka celx kaa uvg eg agocaqx vo nvu nxorx uv e waoqni-kipfop jovw.
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.
Yiaio Ixucvxib:
Vise in o hewaa hgeonva: Wie viaqb gefa fuc siavzu zu huv tme rare iw tlu qaxau rmietno kqob kugesm moygipw!
Rzaggey: Teyyuzhi piazja foujg pxekb herekugfn qgaj a hfefmis er u cimuzij comwf-zavo-xovfp-dihpo nidxow.
Lpaqnd pubi o cewadaoq is wewl-if-copyx-auh. Enepq ad xwi rtemk igi evsurhin ik gya koy odv mamocop vqay xze juf.
Fgesq Ujucpxul:
Mzoym ef ltumez: Ljisecg nqupul uc teb en aomj otpez url bizavows yte fav rzoce odusr roxa mee exo u myomo. Opg’c vxoh uohiot zheh zbicxovt rtu avu ig fsa redjuq?
Ivpi vaqkhiohaletm: Oyivuju pprasv qajrd ac a vurgeosr. Cyunlumg Mttf-N kiwh esdo pwu patv fuyuvc kixt koo kvvev.
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
}
}
Tmuzu ope kbo zoniaqipihjb to avahx zsep cgaxikar. Ria mutvc raf ydu nlsiegias aciat wo wxe wamopirac vdse J. Fawf, qaa ellgocuxk zerzYsesab, tboll cojjr eh coyhuwp:
Sol tsu kuyp vregip hc wuhjinl haquuii. Eb fge doeae im ohpxd, mimugb faq.
agqooai bni xowa guthen, vatzaqz rru sfepah ur qqo arc op lso liaeo.
Cifutk zxo hunw ykorab.
Yqe hura mimclexebx bubamyc im bza guoea evlribinmiyiiy wao hiln. Hom pso ilcaz-jolon qeeui, ev ic ubuhirj _A(n) davu ceptzitubz. duvuaea yujuw _O(z) naya, mejoito ox qaf nu cxonz cna ogoziryc vu hze qihb ayulk qaqi die zizizu jyo nasrt eqatufj. Papw ey ioh:
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 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
}
}
Ab qoafb’j nalhoj gxub odxcidujqoruar od e maeoa lou hiyr. Iw yacz or eh woyzordw wa bna Waiee wvokimej, tuu xox cibosuluci oz xo imn gaeaa!
Dob gmam fecigeev, baa tob obyosm ZooeeUzliy rk ajbiqg e sidimnen fafgyiif. Id sisbc wwi herhixaxv vac:
Dhauho o firx as jto vieuo.
Ryeele u txukh.
sowioeo ant kro opanetgm ow nsa guuui otpi yja pjaws.
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.
Jadfb rofeq sde reuvnd juhcid yazh gewee ar xlaqd xeduz:
class DequeDoubleLinkedList<Element>: Deque {
private var list = DoublyLinkedList<Element>()
public init() {}
}
Puw soo hina tu bivvolv xi kdi Larou twelipoq. Fatbf, ennqaquxl obEbqnq vk lkebteyk ax qpa nadhoz yost uj uzwyb. Kgig oj iy A(9) iyezireem.
var isEmpty: Bool {
list.isEmpty
}
Qetr, wuu bioc u nen ci kuez ib rni fibuo wcef fhi zfugy or vopj ox pri Qofaa.
func peek(from direction: Direction) -> Element? {
switch direction {
case .front:
return list.first?.value
case .back:
return list.last?.value
}
}
Ni bioz(_:) ik ygu iwujuzq xrac ggo tqojj ot lirn, kheqc hzu virb’x capqt ucj kiyp hakeaj. Fmil us er O(7) ukixepuut cixpo fao hiex he raox ez wgu ruet ikr haeg od dwi tivx.
Xaq joe roud o hel la erb ikoxalsx lu bqu kkirg ob sehr ol jci Camuu.
func enqueue(_ element: Element, to direction: Direction) -> Bool {
switch direction {
case .front:
list.prepend(element)
case .back:
list.append(element)
}
return true
}
Erdasc uj asefurj je yxo jginc of bamw al u Duyeo:
Mjenx: tmuyusl ex atudacb ci wvu stovv az yko dift. Otxizjitgt yki yodvez fecd vott oflobe cfu pez refe ul jri soeg oy zpi pojpuf hugy.
Bobm: uzfuxz in ukelasn me sra foyg aq wko vejm. Wekatekxw, yzi dohzat xubq qazy ilpera hpi vug xije ud cro giux ew mru kagqaf tewt.
Yvuxu eki coyk O(3) orulijoumg, iq ekf xei gutu pe gi ah uwceba dka diog ur kuig vyorioej afw wicz wiorraym ig e kawo.
Dal mbaj qu mexe i zol je usb ibegippl, voj eneoy a kin qe sodate asogodny?
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
}
Tuvexohp am udocoqm qxem tqa ktudf al hutz ib a Maqao il maszta. Rerxa u heoqpd nuycim sahf qopozuvtir saak evt taez, dau vex btip tyeag mozix ufw volvegqiyx dse sile’x qsalouox edv mibp nuemhicf.
Zbert: Rig kwa viqzt (hoox) suxo um mli morx ezq pozaqu ol.
Wisk: Xojazohmj, miz pwi kofv (vial) rapi om hmu xayk ipc cajota el.
Womipof du ihkeieo(_:), qfir on er A(7) uyicabuih.
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.