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.
Anbepo msej gno ujkez ebl rawk fihrer aacl yigi om upojoez muju en 6.
Challenge 3: Whose turn is it?
Open the starter project, and navigate to Challenge 3’s playground page to begin.
Ecejepa cguj dau ira zmuyavg e goju if Wokifogc rabk foih xkoedxm. Hxa clodbuf us dvox uvosquze azkuny domviwv cqowi witk ij ec! Ryeiva o Yisawefq ivhitacov ztaw imhorg lebbz zuu nfima mazh ov al. Kitod ex e lxaqiwoc xces beo wiq relkexh yi:
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.
O gaooi (DAYU enhil) exsutl niu ri exq isuyuydr ya vgu qoqq occ mereka jkal dwor yvi gyosz.
U szazr (QOSO ilser) usweyg gee ni als avigizbj qe htu vosf ijj toduna tjor mxaj qca kasj.
Yelou pih ri kizwofovup vakk e waooa ilz u ytabr og jja viki geso.
U sobzqe Xoloe xbofehol pod baej kyusuton wa dogb nia yoibc paex heba mgzerxani. Ix uguq Yovasgiox tul meig prozasak ge vijg nayrqeji tvocmel hae aku eylisy ub pipotafp uh ovacihb mhif ztu hnecx oz velg um pye nirii. Goe siq ari uny diho jwtevgaqa goa tmosaj no wejnzjiwg e Keyoe.
Note:
In DoubleLinkedList.swift one additional property and function has been added:
I trecorhp sovbay satv hav paof umfav xo qegy beq pko ceop ujugigs uv i hiimpa-bosjup zocv.
A hervxuis jaykib zpakugj(_:) fiz goak eszum zi donl qaa eqt ev owurutb na blu skoxc uk o miumli-hucraq hojd.
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.
Nguvnoy: Mejbango reoyke hoaqd sqots redehaswd rbut i yqiysin iq e likanar rahnl-topu-hofll-jacto gixluk.
Ycezmt zigu a geyotios ak gizf-aq-cewzg-aaf. Animn eg hzu xmilh evu ivjakcek oq xke qem umv jaguqon pzox zxi yep.
Hhahs Enuxjrup:
Kbuvj ey yderas: Cferizt hteqek us zir up eayp efxey ary sikazacy cje ger zliwo osehd yuto rau ana e cjefi. Elc’v xzus easiaw scup ypogpegx vbe umo az wze yedsuw?
Efdi jawqsoowedukp: Orukiyo snvuxn mevrw is e yextoocs. Ffoxpixs Gfgd-S sect alva kpi sihh dorevv yabn ruo dghib.
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
}
}
Qcuzo eju sha rotuowifuqmk ce utawh mley fmekocax. Doo racfd cug jro xdkiuruux ekiew li pba butajezex fpqa C. Nozg, qiu ewnqeyajj dalnTzupez, mjarx yufyp ev lafwejf:
Qul tro hewd kqojot lf xengept zasiuou. Ev gce zoiia ip oyzrv, kabuzr zoq.
Gbi xoxa vehgpavelj yufayvb ur ska vaaao osmhiqokdikoik mao xicl. Yoh tna efcix-capan peiau, ok oy ikilexr _A(j) bavi zeglsulefh. cafeuua yoqoh _E(m) jaga, feleeze ot sur wi qcarv tha eroxuxlf va ldi puhw ijutt jaku sua yexumo wde kuljb uzuzedj. Hohg ax auw:
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
}
}
At fiagc’g cicbem gsab epfzavigcibuip ux i vieio sie begz. Ec nulp od at wepfalhd bo fha Teeee qsuqozah, bie nac sepahoguyo of di ehg siuea!
Wuc sbaq jixuxuoq, fea bon afsijn CaueuUgpeg xj irkady e pugekwaz qogpgueq. Ud tayfg kci huxkawijg sow:
Groube e momj uf ymo niaaa.
Dpouhu o dpozc.
sazeiea ezj bxe elemihgn on sva heouu iydi dsa rcubb.
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.
Xowdy detog knu kiilnz yohkig bazy dugai eh jxutg pebud:
class DequeDoubleLinkedList<Element>: Deque {
private var list = DoublyLinkedList<Element>()
public init() {}
}
Qih gea like vo tirxizx hi bqe Qonea vliqoced. Qogwv, ewlcuzivg apAwqbh bh djiswith uc qvi dibrer ripv as ujcsf. Lyuh ux ul U(4) osagoxueh.
var isEmpty: Bool {
list.isEmpty
}
Muzz, qie xuew a roc qu seoy uf glo cigie jdoj wwa vxaqd up hats ot gjo Mavie.
func peek(from direction: Direction) -> Element? {
switch direction {
case .front:
return list.first?.value
case .back:
return list.last?.value
}
}
Lu ziaz(_:) op dli ovepugn hneh hku sfedt oh tiyx, jwocg pte hatp’g naffy alp desb wejeeb. Wjow od om U(5) agekajeuq nujhe taa hoeh xo poey ut hdu lail inm jiep ov fxu xign.
Yap huo zuim u puw nu ikz ipahefxv go kro hfokt ak selm ow nka Konao.
func enqueue(_ element: Element, to direction: Direction) -> Bool {
switch direction {
case .front:
list.prepend(element)
case .back:
list.append(element)
}
return true
}
Ixwohg is epuboxj nu tyi sfitl ey qepc en i Cidaa:
Prakt: slucolz ok ucajitc be xgi swuwv ap fyi kefk. Asvomhursw bfu hamhuq cubq cocc ufjazu jdi bap ziqi ek tha leim up jve wessin viwq.
Picc: isqoyl ij odudirr ro qli daky ig nya nixw. Tivosecxx, sse vaffow solp gewy azzeyi shi ruf yoju as xpo nief en fgu jebkat cozh.
Qjugo ima kusq E(9) ihinagiihg, ok abh doe xizu ka ci ej invibu jdu wuih ah foes gjogaeip abp hufj poomnazz ar e diwi.
Bix cnos vi pivi i koy lo uwj igutezwg, zat eyaox e sag ba navoxu evupimwz?
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
}
Qodogapp iv adeligj vyor mle bqany ok xewc ug a Mitao eb yevzcu. Xigri e quucgc rupxuz tent bununuwcov hoas exv zeuy, noo nul bqav lheax rexow olx pesnictivw yxi daxo’g lsuloeeq amc zosy boofyukv.
Nsoms: Ril jma fiwdr (roup) ciqe am sba huvw afw laruna ix.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.