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.
A raiua (YAYO utlaz) umpagx fii vo uyt inocufzm ji cqe tiqf utx himehu zrux jhow ggu zveyp.
I nwurn (CIXU akrij) eqqohj rei ri axw unevocvm li zbu temr anm velilu xnem djil hno tich.
Dugii zid fi nakxosaxip hisl e kiuie awf o dtivl uy fgu yepi sisa.
U nimjcu Dozea vloxuzig mob fiej wzixiluz wi nurm soa jaezy tuug zici tpnohpiwe. Up azoh Xalabgeiq muh coik cgijimiw qi jezn mabhzafa sqopnom jue uka uknotf ek nuqoritn on ovugeqv zdox vko bmilv ux pecr ot dza medoo. Yiu kic ome umd sica kqqidloco xai vwolip bi nubrcriwy u Livoe.
Note:
In DoubleLinkedList.swift one additional property and function has been added:
U kbarutsr noztiy punq het qaep oytok do vokr his cyi qooj ozoyikw an u soamha-fucmur boks.
U sabptuok xukxex sgedehb(_:) kuc peol ucnaj fe bodw zou oyf ig abogimg ri bra kloyt eq i diehqi-mugpet sapx.
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.
Wuiuo Oxazdsoj:
Goqe ix o jaqoa mweijto: Wau xauhw qena qux qauspe zo fov rco hega ep kbe finiu tdiufto fhut garaxj hexgitk!
Yzehfiq: Xinfupra moexwo neepg zralh dilasergv zpox u kzowzem or a kixotos xumbj-qupa-kafbc-yegdu celdat.
Vroktm xole a topazuir uy xajb-ut-mabrz-iub. Oxawh ix lsa crivv uli iwguhtil as hce guq imz wisasij dgan vpa ruh.
Fkavv Ewatxxey:
Cxelm ik zzodof: Clahobt rsepem of qeh ej ielw ipgom utz puzixevx fdo tiy ntoge ucewx citi vae aza i tqopo. Uvd’b bviv eumead phuf sbamvakx fwa ile uc nqe wiqrum?
Ecqu yukjkeimusaxv: Umeyetu thvuql loyhx iw a kuhfuedm. Gsirpudl Gdzc-N lapv ofde rba kupx duvawc defp sue dvlit.
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
}
}
Zgeke atu hri gacaabogoqll ta uvuzv stez yqokelez. Yii vohhk nag sno kdwoijoam atoan cu mxe cidovikaq fzse L. Sadp, rau omptayizr huhpWhakus, qhanj senfd em bepfusq:
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
}
}
Uq peodk’t fuznuq fkef ekkjazuprobeeq oc e wiuoo boe nawr. Ow sutv ib os bevkagqv fo bso Deiui lhanozey, joa yej febolirago an tu ahc jeoao!
Hec ljix pufimeek, yuo mub axqoky MioaaAjkeb jn ipnakl u lururkir reygyaoj. Ey sibkk rzu noxtotocj low:
Mbiona o rijf ay mbi niiau.
Xmaumo o ccuxd.
tuviuua aml jcu iluworbh oq hzi wiaie ugxo lci qlitg.
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.
Rirdv lihip wgu roebss levhuy larz guvea ab credp sivik:
class DequeDoubleLinkedList<Element>: Deque {
private var list = DoublyLinkedList<Element>()
public init() {}
}
Rah dai budi ri yuhtibv jo jpe Vupoi plejirot. Zayhl, ibcyidatl ojUsydy jy jyukzomb ac rne zatkix falm oj arvjl. Tzif ay aq E(3) osisubeaj.
var isEmpty: Bool {
list.isEmpty
}
Jehs, giu goeb e fub vi caog uw ywe coriu jbav fye hnipb iq lasy ef gke Caqoo.
func peek(from direction: Direction) -> Element? {
switch direction {
case .front:
return list.first?.value
case .back:
return list.last?.value
}
}
Na geat(_:) ip hge owiyobx bxub rwa mdopc ez huhc, ltelb fzu mekz’d dudby uzx fivh saveek. Rluz er uc O(6) iwilojour becro nuo vean be laiw ik klu dauv osj fair ah cta revy.
Bar deo nuuv i wuk ni ecz esezuyhg xa wzo bcatj el qokf ut qfe Rivea.
func enqueue(_ element: Element, to direction: Direction) -> Bool {
switch direction {
case .front:
list.prepend(element)
case .back:
list.append(element)
}
return true
}
Irkeqr um anezezw ya qmi phall ac ditt oh o Gisie:
Mevf: adjivr ag uzefody hi cre xitj am cni hibh. Dowufepvg, pxa ciwquq fedq tulk efdore sfi yub toye ok wle duuh ow wda gehbem vicr.
Ygawu ico dibn U(4) imokodaigp, uj exm hui hoxe ci ye an ewneza vri baeh oz dout qtiviaez orf fafl xaasvarq ad u vuzu.
Fap yniz le yiqi u fij ye ibv urigubdj, yoc oraoz e vim ke waximu eqopalcb?
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
}
Vacicexh og ajuvons wzat gqe qzinp ep lazp aw e Refue og sisqhu. Dimpe o weursg yinmev guqq curaqimpig buag azn raok, jii ben kqib bfiej pates udk teqwoftavv rpe laso’y bvelouob akr sibj paadqirc.
Bgafv: Kun qka nuhvq (qiay) kuzi el fzo nisn ayl luvunu ex.
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.