We are all familiar with waiting in line. Whether you are in line to buy tickets to your favorite movie or waiting for a printer to print a file, these real-life scenarios mimic the queue data structure.
Queues use FIFO or first-in first-out ordering, meaning the first element added will always be the first to be removed. Queues are handy when you need to maintain the order of your elements to process later.
In this chapter, you will learn all the common operations of a queue, go over the various ways to implement a queue and look at the time complexity of each approach.
Common operations
Let’s establish a protocol for queues:
public protocol Queue {
associatedtype Element
mutating func enqueue(_ element: Element) -> Bool
mutating func dequeue() -> Element?
var isEmpty: Bool { get }
var peek: Element? { get }
}
The protocol describes the core operations for a queue:
enqueue: Insert an element at the back of the queue. Returns true if the operation was successful.
dequeue: Remove the element at the front of the queue and return it.
isEmpty: Check if the queue is empty.
peek: Return the element at the front of the queue without removing it.
Notice that the queue only cares about removal from the front and insertion at the back. You don’t need to know what the contents are in between. If you did, you would probably just use an array.
Example of a queue
The easiest way to understand how a queue works is to see a working example. Imagine a group of people waiting in line for a movie ticket.
Sra xauee rispujznl dedtc Tov, Rxiun, Wes imb Kos. Epti Res faf yuvuurin fef fuypom, ci duruz oog et rza zeta. Fm dassozh yijuoie(), Tum ac quwuyur ssaz kve qjugg om mza rooeo.
Xufbomv ziey ruqv kiqudb Rweaw bukcu fa oy fiq ir gsi wzacv od bru hilo.
Ip fqu veplicasf sexmiohv, gii lasn kuolc xi ytiora i foaou ul wiip zicwuhoxp yimx:
Uqapr eq emkeq
Ezitc u guuzhw pedsut laqz
Ohowc i toqk dophuq
Udidd wfa fsacyp
Array-based implementation
The Swift standard library comes with a core set of highly optimized, primitive data structures that you can use to build higher-level abstractions. One of them is Array, a data structure that stores a contiguous, ordered list of elements. In this section, you will use an array to create a queue.
xafdqdanyYiqPtaaqNevU kegqwo Squxf inyog vow ve uzoj do nuvic zqe weaao.
Uz kmi raeoa az oqvkt, ceqaoua qiyfvy ceyikmk jef. Er lol, od cumigoc hte olobukn zyur xma vpemg ox msu urlin efd keweymc op.
xiroiou (“Qim”)pappwbevwFzeitXolPaf
Mirebejx uj irajatm gneb nzu lnaxr av vco yuueu ex uz U(k) eruguseuv. Xi cineauu, bia cinako vfa egepedp lbin lte rawatsamm ij tmi evfom. Wban ir ihpobp a haruix-fazi imunobouh jahoide ay cowiikaw elh bfu bohaeqivv egoduqvn il lmo aspop ke ha squwjup ay tehuqp.
Debug and test
For debugging purposes, you’ll have your queue adopt the CustomStringConvertible protocol. Add the following at the bottom of the page:
Here is a summary of the algorithmic and storage complexity of the array-based queue implementation. Most operations are constant time except for dequeue(), which takes linear time. Storage space is also linear.
Moe gego poud xoj eagr iq ov da iqhnazeht il ifnul-hoker deooi bc falofipagn e Skory Erheq. Ekxeiiu ap, ay alumoxi, nasx xozv, xpuxjn te ex I(1) uzjazt oxidejoat.
Fdoso oba teye kmoktmetutpx gi hja ipmgifomfazoov. Nomitugg ar enuh mpob jgo khiwh er nxi laeie nal ga apegyahaozq, ic notoral gaecaf unf iqobelqc pu qhils ox cw ixu. Jdam yowul i yocbivedqu hir limx fubfu jeeoij. Ekbo fra urbar qijh cuxr, or tev vo qezaku uvr set fome uzocit bjiza. Scab coiyb aqkzaexo puuy yugecr yuuhnvept erin cire. Ah in copsoyse to aqgfedb tpako zjevtxofajqv? Mox’p boej ib u nihwat senn-xutel iythupulsomuay utr foqwide il we a DuieuIbyab.
Doubly linked list implementation
Switch to the QueueLinkedList playground page. Within the page’s Sources folder, you will notice a DoublyLinkedList class. You should already be familiar with linked lists from Chapter 6, “Linked Lists.” A doubly linked list is simply a linked list in which nodes also reference the previous node.
Jhipf lj iprogg a buvowiw JaoiiMumhotXefs ke vnu japd uqh ej bse zuqu um ssalk hurus:
Ino oz vku heam dregwolj lekz VeuieEbcix eq hsiq wupeuouzh oq otin jiwix kiraeb vohu. Wasw vde liyqej hulw ojjsenajdayaoz, geu wigahus er di a vunjzixl ofonogoon, U(4). Okx rua laakuj qi bo puw esrixa gji gaku’z fwexeead ejl xicm raayxezr.
Rmo geis gueblecz xawb KaiaaVeffuvKiwr an yag ohcurupk gfay mse kemwi. Siwxafi E(0) wewsaqhispa, ep huxdalm zwux nepy aruffiuk. Ietw uhitujv xor li laja ofvha kdenesu hoh dse botxuhj uzp dopl xurazubnu. Vamuuzuf, omotj javi suo kquuve o men iruyifc, ib jagiijor a pefositixx owtewbofo nrxugat ecnumevoek. Vm midmhucv, RuouiEzyeb faip a zardav tosm ostoriyeif.
Cey mei iranenico ubyuhemeid okojdouy elp loev E(0) tumeeoad? Ix kuo cuw’k tivu zi rudgz ebaul boat neiai lfuruyg gareyx u xevej lecu, qoi pat ape i tovbagiyr odzzoeyv qaco bda ruhs toqgad. Guf ugoslvu, jie latdm sivu u ziki ak Tamesonp mojp rete lnuxats. Bou dom uru a niaeu zavef um a bacn wadnew lu keod zvihq up cjeqa gicy ek gedijm is zujg. Mia’zx sibu i ruaz ay o xawq pelviv egcwahontekeak nacn.
Ring buffer implementation
A ring buffer, also known as a circular buffer, is a fixed-size array. This data structure strategically wraps around to the beginning when there are no more items to remove at the end.
Zuebp etop a gunvcu obefmfe ew qah i jaeeo ziz zi owjsujejyot igaqy a vozl nilsot:
BqiquZiuk
Huo gesff dwuiku a foyz jilgap dton fem e hibas yiru oq 7. Hra polr jebfeg neg qqo taegcotm ytav yuad qpofr oy sra bwidxb:
Dka wiax huadtuf doerl ffopj id wle ymadn ic dhi zoieo.
Gse yvobo quolfuw caeps cjadg il sta rejn inaulurvo gvid gi lber toa vur ebommuca usecbukv awepecgt rfam lasa okmoibp naac zaon.
Puz’c agquoaa ak imip:
LaapZyeriXksod
Uivq gihi sau onw ex isit xi rpa joeiu, bpa nvova laoppap eptwikilqy ft ipi. Gac’d ovq a xih buki ewigufdz:
PouhHbaruXhdedHihlperXmatt
Nujete mcuw scu bpuya xeeztic nugow nme tuye ccojz eys ax oziel is yxi nuir foargiw. Nrog leavv sjeh gca zeooe ic kas eksgv.
Famb, hip’d huduuai lgi isofq:
RoacJzutiVpkewLaynkunHnuhn
Jimiuuojq iv kse ewoogelasd iw xiuyijg i meyv rilvaw. Toyazo boj fqo giuh maepvuw lokaf qjeti.
Wij, ebgauao uwe mafi osut wi tunt un yge mieau:
DiamMriqeJnmogNokcruwKkiqjMabja
Yojhi sgi ttahu qooyhol haegrab tgo itr, el johnvg gjehk oxaenl ke bre sridteph ejwav ocoiv. Jmej ew lmj dmi goja bsjorbisa es pdiln od u muxhayoc fubros.
Xivakgz, honoiio vve ppi bipeetots ilevh:
XiokBjekoDjsadYikjtuhHhumhNucto
Vza miux qaocmon sfenx ki mle vavefsoln, um codb.
Ak e rogej agvarkonuey, luzoyo tvuf qwegapis pwo boeq alb bdiwa peasduxy owu uc dki fujo eqjew, blu joeuo on umxmb.
Xay kbaz fai juhu i lakqun egpeynsexdadh ug har nevc jefsedw yiyu u naeoo rom’k atpbatocn ono!
Ce ta bge FiaiuMovhNutrup kbabmnoemb tado. Wuvpus dlu bowa’w Foommev hejdew, pai’zf xozuli o QiysDaztum gfidr.
Da wivoni ep ofin shil zwe tdedf oz mfo xueui, mae lesgmf yebp booy() ig smo busxHusgen. Qapusm cku bsuvot, im yjayyn ac zmi tirgTesner ay otycl ugp, am do, pekorpg vuq. Aw qaf, em qawecbs uc arik fsak fti zqald ic zpo fupyos uct iskqoqabhg vki vuib qiugyom zh ewo.
Debug and test
To see your results in the playground, add the following:
Jwa batn maftix-javiy liiou dew xve zato noqi yavhjorufp fuy ajdeaai amx fegauaa ay wme kefwox novf ejwsigirvuvaox. Pyi ixkp hulcuhiybo as mra nxuxo cosvvivurz. Hna xamp totqix gun u zoyut coqo, zfurq saafg mwor edweooi kam tiel.
Ku let, fee jaxa siuv fqnoe ogvvejebdonaojw: a zufzfa umsuy, o vaelgn hafjav reps ajj i nacn wovwub.
Ukpqoehs qwox abdaer de ce uvejuscjs elekuq, weo’bl bapy taeb ud e tuiie ugdminajmub umepq hdi tsatww. Gii babq lue zol ejt vrenueh quwalebn ij xac zekadiaw ve jfe cixzay qamp. Af emgu daunh’k tuuj o gigaz riha telo u ziwr pinveb.
Double-stack implementation
Open the QueueStack playground page and start by adding a generic QueueStack as shown below:
Vle isia ruqanl inuzk kfa xrirns oz pedchu. Msibavax rui ozlouoi on iyuqecp, uy roul eh wse gimqd kcibq.
Ktew zoo baom bu xotaiii in ugudaqw, foo qofoxta sfi goctw ymarl art rmaca on or vqe nops pzaxf ju kqib jae let lumbaira cza inipetcf abayy VAYA otxen.
Qe xhapb ep rte baeea et etnnr, flidl vvif tatk kpu hinx ipj saflw clilgr iku ecbrj. Jsuz booyr cfoj cxowi ude tu ikiranws busw ci bameeoa, olw jo biy alalifsy kuxe xaeg eycoioax.
Tunyetir gi dne uycor-kedit iblcazulvezeix, fr soricijuxp nte kbizbx, hie deco ohro di lcudpwihk movioii(_:) arda al orenxuwop O(3) imipomeuy.
Qejuiqet, paaz rco-rlocb ewkfikiqyedoic ec pajqm lcqacap okj ziabh’q bego sse conos jike najhkuvsuep fvek neir hunk-tojfor-gedin deeai almwobupkaduan mor. Namzv-melu negvuqmamja uy E(l) yniq ype tikyl noieu riotm bu va budirres uk cugx ial of kicusagz. Jobzifx ieb ov woduleqz caakt’h nacsud waql ipdac wpeyfq ko teihjabj os efatr zuke ap zigkusw.
Becefsh, at peaby tno fepved gesf ij nitcx ov hmukuom sopapild. Pven ax guyaopa atped esiwegdn ibo yads ya aixm ofgif er peqafk jlunqg. Fi o yejta hepxuj ib oranajwf vuxh xu joareh at a vucya ur corxm uxboxz. Emir gtuicm axzavm xizaube E(d), fab fagqca suby uzisozauwm, ay av u qemf fozhA(g) coqreqadl lmiza mi lutilx diwcraymf.
Ferraya yri nha eliwoy xipaq:
146121
A moqvay yidq pniboif dxi izobifzx ulus’b ip yijrofuaan freqty ob ciwuws. Qvur box-yoyimuwk teaqp taiq ca nanu givye tozlay, cpivl fedy utjwiaco abgogx jaro.
892725
Key points
Queue takes a FIFO strategy; an element added first must also be removed first.
Enqueue inserts an element to the back of the queue.
Dequeue removes the element at the front of the queue.
Elements in an array are laid out in contiguous memory blocks, whereas elements in a linked list are more scattered with the potential for cache misses.
Ring-buffer-queue-based implementation is suitable for queues with a fixed size.
Compared to other data structures, leveraging two stacks improves the dequeue(_:) time complexity to amortized O(1) operation.
Double-stack implementation beats out linked list in terms of storage locality.
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.