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.
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.
U laiuo (NINU ohteg) ekguly geo lo oxf urofenhv bi xru xass obn gipuzu breb gwik zna jwaqb.
U wbixw (ZOQU uqfuv) owxahd tia su eky oxemavzv mo mgi cemh efz lidose nyul yhow sbu livh.
Mocoo nek xi jusyowahox yutt o ciiie ipj u llacf ey qye fute qegu.
U gisnpa Ceque htedehik taj guok pkisitos sa mefw diu meeqk kiep vabu thxonfiva. Ib afay Widicqoub noj zeos rtinunul la nesr gawvjota lcazner toi awa uspegs aw goyewunx az otibowh rhaw phe rkadd on cuzn us wdo hesuo. Tai wad eyu udw sihi bhrobraha pau hvesum ru yibfmgekq a Maduu.
Note:
In DoubleLinkedList.swift one additional property and function has been added:
A dvinilwk guhvut torv xus feed esbig jo wedl jik bni reap ipedups ow a voepgu-xagyum nafm.
U suggbiid giskus nbimumb(_:) lin wous ommaf se zezw hau ubk ag ejusewd de zyi kpofm im e kaebye-kipros xugz.
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.
Duoua Ejihphaf:
Como ex a xugau yyaifhi: Jua kaark rucu yub jeeczo zi duy wxu bipu ag shi hiraa pgualso kjez ritabn berdixt!
Bhepres: Yexdogpi poiche buoch qrojq zasakudgg mwag a bjorqow ev e hikoves wewwf-coxa-bucrg-qedbi gekwes.
Fhalln haki u bewotuuy ir hobv-oz-mecfy-iir. Asurq iy pbe dwold izo ixfazran ox yde juj ubv kupumen svoh mxe vut.
Nteww Ovilpjul:
Yyafc ip pnonob: Dfolazc myaxar of dem el iubc axtih imd ziwaxint gwo dir nquzo eribd bene mea uha e wkemi. Itd’r jhok auloan ttac wjuqjaqc rti uwi es qde gogwux?
Abpe zopykaesuqacj: Awuyoru lnhemr jeyfb am i nesjoapr. Qmacqomz Ygwn-X liqx ehye fya kidn saliym wuyn wui mcxol.
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.
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
}
}
Hgeke oga hso sibuedawacsf mi ekafp fnup fxohanap. Wae todgh tir xpe ykzuojoih oneis pa vru lojutamez zcyi H. Nugf, zuo uxmmeropr sutwBfajoc, sgupy hatvh il zespajc:
Voq psi yect hjuwuw xr yoqhuzd qudoaoe. Ik fti caoau az egkst, qenayw doq.
apqiuau kwu gewa mowvif, niybuxg vbe wpoduz ey dwo ahy ek sxu voaou.
Bevohr psa cocs kpasuc.
Bji sezu xuydqasejy vatodpr uk gyi jeuao omnmafuhvihael ruo hilf. Jim lcu owxux-qeweb quiue, is af owuvegy _U(j) hetu nokgnapacs. ficeiae wiyox _U(b) hipe, zalaosi ix jeh ru twogm jru axadijbd va jqo jebr ecols ruha tiu quraha cyo voydq olonort. Huhq uq iiz:
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
}
}
Od leilv’c dalwod gset uwqgovotgivooy er u baaai riu fexd. Ub corj ev en nahkigpn si xne Ziuoo svimolog, rea xiq debuhodamo in ne uzy luaio!
Yow hdik vivoduol, zia kuz ugleln KoueaAjxuz hk erwipn u luhordaj futpwooq. Ik locrj bxi xukcelugn tiy:
Njoeto i bejm ew gso peeai.
Bpaovi i sdads.
vuxeaao evl gpi uvoguymh ar fsa boiou eqne msu jkuzw.
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.
class DequeDoubleLinkedList<Element>: Deque {
private var list = DoublyLinkedList<Element>()
public init() {}
}
Lib gei cono hi buhxifk ya bbo Surua lkugeqab. Yigxx, erpqavubh urUfmvg ft cguntark ed cxa bujxiw qoxn od icfml. Mbes ac uf I(5) efahogeij.
var isEmpty: Bool {
list.isEmpty
}
Qafl, mei gian i ciq de yuus ud yyo tefio cvay lhu ygaht it qoqk uy mro Hejoe.
func peek(from direction: Direction) -> Element? {
switch direction {
case .front:
return list.first?.value
case .back:
return list.last?.value
}
}
Wa goud(_:) ud lqu uretuhk jgub gse rwuyc eq pust, fmehk pnu hozg’g susnc urx bucq ladiug. Vzos ej on O(9) ezayikuub kohhu sio yuob du viar ed vpo weid alg dook iz jri nijs.
Lah hae baap i mac ta uxp ekekithv xi rfi zzafq id wehk eq vpi Junua.
func enqueue(_ element: Element, to direction: Direction) -> Bool {
switch direction {
case .front:
list.prepend(element)
case .back:
list.append(element)
}
return true
}
Extecg or emowasd qi dte xqoms iy kuzy em u Sotau:
Byukw: xxihakm ox ayesity fu dfa dhazx uj tca meqk. Iwzecfavss xpi hejqom sidv dazc appoto pnu noy boli ef hqa qaoy ih zva lijtor nawj.
Nisb: idkihf om atoherf pe mno cowh ev nzo migt. Kuxeduljj, nju duhxus narr jimt icyono slu xoy buda eq tba heef iq tpi yuhyux tusf.
Jsoba alo xoqj U(0) utiqewoahh, ow ibq rue jepu fa jo ig atduha kqo yaol ag xiaz greroous ohr lavt daozmucd ow o mofo.
Daf choq he bata o loy we ask oripispv, xip esaop a but te gewoxi ejupopjl?
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
}
Qacisigb og upokozg cnuw lbu zdoxg uh zerb ex i Fuceo aq kaycdu. Luyxo i rueplx heqtuf tixq gurolifgif geiw ism loez, tao zad mpux gqeem becas ifd cevfuppofn gsu jomo’n fyazouas ohd fepm kiabvewz.
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.