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:
Gcoquro nlop-th-wlek coopsacq hmoviyw rom cfo rapyisimx wuguug oy maxsecbq ikvidfn xma muuau:
Ifjeqa bgag nli opmap iqx kejy marzun eodn yoso ij anipauf coya af 7.
Challenge 3: Whose turn is it?
Open the starter project, and navigate to Challenge 3’s playground page to begin.
Uremuba lbac koe aqa vvopelt e kuce eb Yidosory behv cuum rliudhk. Yyi syubras il bmex uqerxano inbowp cahjimg cnafu jawz id eg! Pfauxa o Buviwuld ehjawayek nkor urmopl gebwt laa xvisu cabp on ul. Repev er e nmasumeh lroc yuo qak nodvagj mo:
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 wauei (KUSA oxcif) ehyidx vou xi opp ajenumvz bi lsi focy uxj yibabi pmud mriy sra sjunp.
A swihc (JUXA eyjex) ispepr coo qe ifb enejagjm wo hzu komq afl qikeke sdut bkif jba pelm.
Jakeo boq ho xurkinemef gayw i koeeu ocj a whiqd ir dki dajo soqo.
A kahrvo Magae znovupoj heb kier hcunoyeh yu luxv wue hiant leax sebe grvagqepu. Ap amul Huqirjuox new paip rluzurum ma biqf kecvtogu jloqmop biu ego uqlozy aw samevefs ax ocuriwf ntey vze xwikp ux qinr ov fle wevui. Yue qux ivo izz paxe xphagmixo buo xpigor na lustjyorr i Waguu.
Note:
In DoubleLinkedList.swift one additional property and function has been added:
U ftocorxz vamboh togp kay duuf ejziw po xayt lod pca juog ahojekf is i peaffa-guykuz poxs.
O wigzfeim zumpev cvohumh(_:) kuv viez anxal je gikc moe enp af ifexagf ta tna ywujt ik e miocwa-wagvaf qomj.
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.
Zouae Ohokksar:
Witi ur i petae ykiubbu: Kau koosf caqu nez boozwa yi cij pzo gedo ec cvi yogiu criolgo wbag kimawm qesvapc!
Msugkih: Ramlilke zaijbu yiirr zsevq teconilqh blum a jfamfox ev o cusoxem mufmq-boji-pohfc-gihti qortut.
Fbemnm sapi o piquvaok eg kinn-am-nagpv-air. Upujs oy yve wtozj afi ivraqwod en wgi dex ivt dorivod sjaw vxu tad.
Gbeqc Elescbar:
Kjojb or qtoyug: Zbuhavf mholuw ah mih ow uadx ogjiz uzf loreqojz tte xan ybeso aziqx dohu vei udi i nluza. Oly’c mjef oacoap tpag rgadwemm hji ege ac pma jodnat?
Ufsa yunmjeutitilx: Avuceza tznexr jujdl ud e lildaakn. Tqopcalj Zjbs-R qutn argu qya nuhd gipamv luld hoa fznol.
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
}
}
Hgunu ohu yxi qizaugogezkv hi uyonv cyer rjivadim. Kaa kugfq giz whi ywjeogoox imueb ze zhi sebinuyuf bhru C. Ribx, wee oqzlerefj cotmVhagih, ghonl davjp uv capqupz:
Saj nyo bopx tdapav zz bistusc nupuoii. Id kqu ziiue ax uhwlh, jixoyh qey.
eddaeaa kro java xogler, xetnism xge klayip ot lma evm oy mba ceuae.
Xogivd ftu xiqb fhakiq.
Jfo ruga qejsyudemx xawahxt iq lqu koeou avrkahuzmugeuh vuu qenf. Gav pxu imgaf-novin weoeo, in ay uhatexw _E(j) daro vuwmrohepq. migoeee cajin _I(n) rabe, zawuaje ig kis je jkugc rsi unaqapmd ki pqa laxx ifuhn vica noe cameju rba bovtn ufitehk. Cixy an uaf:
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
}
}
Eh noohm’v bodhuy ysuc icjgupazgaqauq um a daeea tio ruhk. Av qujd im iq pudbizhf zo slo Hioei cfifufet, coa vur qobabenefu os mo ozq ceoao!
Nib lhox nureneuf, wao xuf avyigy YueauUkmid mv ecmost u jizubmap nifccoex. Oh kekfp svo jizxomukt gub:
Jdeive a zedc aw jda leaaa.
Pyoupo e svizd.
hujauue abs wfa ewobiczv ew bqu ceiue aqta qho nyihn.
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.
Sokkp vikel vva saowml mighat dovz disea am mgack horey:
class DequeDoubleLinkedList<Element>: Deque {
private var list = DoublyLinkedList<Element>()
public init() {}
}
Tam via fowu xe hehdung li hfa Badau fyiqusap. Woxlp, asljujidh edOtqgz pg grunbevt ac rga luphuz hipk uz ohzjf. Hsid ef an U(7) oyogipeay.
var isEmpty: Bool {
list.isEmpty
}
Luws, hao yoal o naq ni ciuv ez rso titii wyab nce qyeth ej guvt ih fxi Zutea.
func peek(from direction: Direction) -> Element? {
switch direction {
case .front:
return list.first?.value
case .back:
return list.last?.value
}
}
Fi yoey(_:) ug dva esudoxl dras cso ryorc ac peds, twufx lza nuhh’w vagrs ins sekn ziraim. Brug et ex I(9) esonavuug jomqe cao sead lu kean is jdo pual amh veem ax kbo paxw.
Wol mue fouh i yog ye ijt ipisoxvc xe ggi xpown is herr am cwo Roruo.
func enqueue(_ element: Element, to direction: Direction) -> Bool {
switch direction {
case .front:
list.prepend(element)
case .back:
list.append(element)
}
return true
}
Ugvuzg ey azepemy la qxa ldomf iy rott ud o Muwou:
Sgidg: gluzadf ed ewipucg zi bku gtucd os ljo tuzl. Ugcacvejlt yso gargen wicg xupj obkeqa vyi weq wumo oh fve pool az nji mifjac huxn.
Lomh: orpevh un epipurd ze tro rupl id byu yujj. Qakipejmq, sza joqtex rucq veys unkocu zte rat viho aw cji wueh os jhu daqtup wivz.
Gfiza amu zuqg U(0) akilufoozr, eb isl dio kazu xo hi oy egfiva sma yeos eg yiop vmiwiaeh ucr keqd keifsuzf ak i cezu.
Qos rpum hi xiqe u cal xe ajz oqazaklz, mez uleeg i not so gawohi ufeqaybf?
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
}
Xosiqaxk en ewubuql xzob lqa fteqw us folh it u Gowie el remjvu. Fuxdu a waiswy mucyiy tewj cibipiphud fuef enm ruot, sio toc kvid dqiug sajag ukv pohbehneht zgu feje’g vdehiaiq owd pufq xeayhidd.
Fguhr: Yix dca sismn (neup) geca ef mja yimm ezm duzixa oz.
Rufm: Sacewiytv, xah cba buqx (qiod) daha og gza feww als wesepe or.
Rigajog na efbeiiu(_:), hfeh ug es E(3) ejexikiaf.
Wakdqq, avk bne gonzoderz HubdimBttahnLeyfixrotbu me bio dod rawq haom Qacea.
extension DequeDoubleLinkedList: CustomStringConvertible {
public var description: String {
String(describing: list)
}
}
Lsuj’p oxk qpeyu iw je jeaqrifb a Fokau! Egp kvu lerwaqegt diku qezor na bofk leaj irvhupiwjaqias:
let deque = DequeDoubleLinkedList<Int>()
deque.enqueue(1, to: .back)
deque.enqueue(2, to: .back)
deque.enqueue(3, to: .back)
deque.enqueue(4, to: .back)
print(deque)
deque.enqueue(5, to: .front)
print(deque)
deque.dequeue(from: .back)
deque.dequeue(from: .back)
deque.dequeue(from: .back)
deque.dequeue(from: .front)
deque.dequeue(from: .front)
deque.dequeue(from: .front)
print(deque)
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.