Queue (abstract data type)

Queue
Representation of a FIFO (first in, first out) queue
Time complexity in big O notation
Operation Average Worst case
Search O(n) O(n)
Insert O(1) O(1)
Delete O(1) O(1)
Space complexity
Space O(n) O(n)

In computer science, a queue is a collection of entities that are maintained in a sequence and can be modified by the addition of entities at one end of the sequence and the removal of entities from the other end of the sequence. By convention, the end of the sequence at which elements are added is called the back, tail, or rear of the queue, and the end at which elements are removed is called the head or front of the queue, analogously to the words used when people line up to wait for goods or services.

The operation of adding an element to the rear of the queue is known as enqueue, and the operation of removing an element from the front is known as dequeue. Other operations may also be allowed, often including a peek or front operation that returns the value of the next element to be dequeued without dequeuing it.

The operations of a queue make it a first-in-first-out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that once a new element is added, all elements that were added before have to be removed before the new element can be removed. A queue is an example of a linear data structure, or more abstractly a sequential collection. Queues are common in computer programs, where they are implemented as data structures coupled with access routines, as an abstract data structure or in object-oriented languages as classes.

A queue has two ends, the top, which is the only position at which the push operation may occur, and the bottom, which is the only position at which the pop operation may occur. A queue may be implemented as circular buffers and linked lists, or by using both the stack pointer and the base pointer.

Queues provide services in computer science, transport, and operations research where various entities such as data, objects, persons, or events are stored and held to be processed later. In these contexts, the queue performs the function of a buffer. Another usage of queues is in the implementation of breadth-first search.

Queue implementation

Theoretically, one characteristic of a queue is that it does not have a specific capacity. Regardless of how many elements are already contained, a new element can always be added. It can also be empty, at which point removing an element will be impossible until a new element has been added again.

Fixed-length arrays are limited in capacity, but it is not true that items need to be copied towards the head of the queue. The simple trick of turning the array into a closed circle and letting the head and tail drift around endlessly in that circle makes it unnecessary to ever move items stored in the array. If n is the size of the array, then computing indices modulo n will turn the array into a circle. This is still the conceptually simplest way to construct a queue in a high-level language, but it does admittedly slow things down a little, because the array indices must be compared to zero and the array size, which is comparable to the time taken to check whether an array index is out of bounds, which some languages do, but this will certainly be the method of choice for a quick and dirty implementation, or for any high-level language that does not have pointer syntax. The array size must be declared ahead of time, but some implementations simply double the declared array size when overflow occurs. Most modern languages with objects or pointers can implement or come with libraries for dynamic lists. Such data structures may have not specified a fixed capacity limit besides memory constraints. Queue overflow results from trying to add an element onto a full queue and queue underflow happens when trying to remove an element from an empty queue.

A bounded queue is a queue limited to a fixed number of items.[1]

There are several efficient implementations of FIFO queues. An efficient implementation is one that can perform the operations—en-queuing and de-queuing—in O(1) time.

  • Linked list
    • A doubly linked list has O(1) insertion and deletion at both ends, so it is a natural choice for queues.
    • A regular singly linked list only has efficient insertion and deletion at one end. However, a small modification—keeping a pointer to the last node in addition to the first one—will enable it to implement an efficient queue.
  • A deque implemented using a modified dynamic array

Queues and programming languages

Queues may be implemented as a separate data type, or maybe considered a special case of a double-ended queue (deque) and not implemented separately. For example, Perl and Ruby allow pushing and popping an array from both ends, so one can use push and shift functions to enqueue and dequeue a list (or, in reverse, one can use unshift and pop),[2] although in some cases these operations are not efficient.

C++'s Standard Template Library provides a "queue" templated class which is restricted to only push/pop operations. Since J2SE5.0, Java's library contains a Queue interface that specifies queue operations; implementing classes include LinkedList and (since J2SE 1.6) ArrayDeque. PHP has an SplQueue class and third party libraries like beanstalk'd and Gearman.

UML queue class.svg

Example

A simple queue implemented in JavaScript:

class Queue {
    constructor() {
        this.items = [];
    }

    enqueue(element) {
        this.items.push(element);
    }

    dequeue() {
        return this.items.shift();
    }
}

Purely functional implementation

Queues can also be implemented as a purely functional data structure.[3] There are two implementations. The first one only achieves per operation on average. That is, the amortized time is , but individual operations can take where n is the number of elements in the queue. The second implementation is called a real-time queue[4] and it allows the queue to be persistent with operations in O(1) worst-case time. It is a more complex implementation and requires lazy lists with memoization.

Amortized queue

This queue's data is stored in two singly-linked lists named and . The list holds the front part of the queue. The list holds the remaining elements (a.k.a., the rear of the queue) in reverse order. It is easy to insert into the front of the queue by adding a node at the head of . And, if is not empty, it is easy to remove from the end of the queue by removing the node at the head of . When is empty, the list is reversed and assigned to and then the head of is removed.

The insert ("enqueue") always takes time. The removal ("dequeue") takes when the list is not empty. When is empty, the reverse takes where is the number of elements in . But, we can say it is amortized time, because every element in had to be inserted and we can assign a constant cost for each element in the reverse to when it was inserted.

Real-time queue

The real-time queue achieves time for all operations, without amortization. This discussion will be technical, so recall that, for a list, denotes its length, that NIL represents an empty list and represents the list whose head is h and whose tail is t.

The data structure used to implement our queues consists of three singly-linked lists where f is the front of the queue and r is the rear of the queue in reverse order. The invariant of the structure is that s is the rear of f without its first elements, that is . The tail of the queue is then almost and inserting an element x to is almost . It is said almost, because in both of those results, . An auxiliary function must then be called for the invariant to be satisfied. Two cases must be considered, depending on whether is the empty list, in which case , or not. The formal definition is and where is f followed by r reversed.

Let us call the function which returns f followed by r reversed. Let us furthermore assume that , since it is the case when this function is called. More precisely, we define a lazy function which takes as input three lists such that , and return the concatenation of f, of r reversed and of a. Then . The inductive definition of rotate is and . Its running time is , but, since lazy evaluation is used, the computation is delayed until the results are forced by the computation.

The list s in the data structure has two purposes. This list serves as a counter for , indeed, if and only if s is the empty list. This counter allows us to ensure that the rear is never longer than the front list. Furthermore, using s, which is a tail of f, forces the computation of a part of the (lazy) list f during each tail and insert operation. Therefore, when , the list f is totally forced. If it was not the case, the internal representation of f could be some append of append of... of append, and forcing would not be a constant time operation anymore.

See also

References

  1. ^ "Queue (Java Platform SE 7)". Docs.oracle.com. 2014-03-26. Retrieved 2014-05-22.
  2. ^ "Array (Ruby 3.1)". 2021-12-25. Retrieved 2022-05-11.
  3. ^ Okasaki, Chris. "Purely Functional Data Structures" (PDF).
  4. ^ Hood, Robert; Melville, Robert (November 1981). "Real-time queue operations in pure Lisp". Information Processing Letters. 13 (2): 50–54. doi:10.1016/0020-0190(81)90030-2. hdl:1813/6273.

General references

Further reading

Read other articles:

CZECHOSLOVAK GROUP as (CSG) adalah perusahaan induk teknologi industri yang mencakup aktivitas lebih dari seratus perusahaan dan perusahaan perdagangan yang sebagian besar berbasis di Republik Ceko dan Slovakia. Anggota grup yang paling terkenal adalah pabrikan mobil Kopřivnice TATRA TRUCKS, di mana CSG memegang saham mayoritas. Selain industri otomotif, perusahaan induk beroperasi di sektor kedirgantaraan, kereta api, pertahanan, dan sektor lainnya. Kantor induknya berbasis di Praha. Grup ...

 

Overview of the use of capital punishment in several countries   Maintain the death penalty in both law and practice   Abolished in practice (no executions in over 10 years and under a moratorium)   Abolished in law, except under exceptional circumstances such as during war   Completely abolished Capital punishment, also called the death penalty, is the state-sanctioned killing of a person as a punishment for a crime. It has historically been used in al...

 

المغرب فيالألعاب الأولمبية الصيفية للشبابالرمزMARاللجنةاللجنة الأولمبية الوطنية المغربيةالموقعwww.marocolympique.org باللغة الفرنسيةالميدالياتالترتيب 59 ذهبية 2 فضية 5 برونزية 3 المجموع 10 الظهور في الألعاب الأولمبية الصيفية للشباب201020142018ظهور صيفي201020142018ظهور شتوي201220162020 شارك الم...

قرية راند ليك   الإحداثيات 42°56′19″N 73°47′23″W / 42.938611111111°N 73.789722222222°W / 42.938611111111; -73.789722222222   [1] تاريخ التأسيس 1867  تقسيم إداري  البلد الولايات المتحدة[2]  التقسيم الأعلى مقاطعة ساراتوغا  خصائص جغرافية  المساحة 3.183299 كيلومتر مربع3.185199 كيلومتر ...

 

Yoshinogari 吉野ヶ里町Kota kecil BenderaLambangLokasi Yoshinogari di Prefektur SagaNegara JepangWilayahKyūshūPrefektur SagaDistrikKanzakiLuas • Total44,0 km2 (170 sq mi)Populasi (Oktober 1, 2015) • Total16.411 • Kepadatan373,0/km2 (9,700/sq mi)Zona waktuUTC+09:00 (JST)Kode pos842-8501Simbol  • PohonCamellia sasanqua • BungaPrunus serrulataNomor telepon0952-53-1111Alamat321-2 Yoshida...

 

Berikut ini adalah daftar gunung serta pegunungan di negara Jepang berdasarkan ketinggiannya. Gunung Fuji dilihat dari kota Fuji di prefektur Shizuoka Diatas 3000 meter Gunung Kita dilihat dari gunung Nakashirane Nama Gunung Ketinggian (Meter) Ketinggian (Kaki) Prefektur Gunung Fuji 3.776 12.388 Shizuoka / Yamanashi Gunung Kita 3.193 10.476 Yamanashi Gunung Okuhotaka 3.190 10.466 Gifu / Nagano Gunung Aino 3.189 10.463 Shizuoka / Yamanashi Gunung Yari 3.180 10.433 Gifu / Nagano Gunung Warusawa...

Prix Alonzo-Church annuel Nom original Alonzo Church Award for Outstanding Contributions to Logic and Computation Prix remis Certificat et 2 000 $ (à partager) Organisateur SIGLOG EATCS EACSL Société Kurt Gödel (KGS) Date de création 2015, première attribution 2016 Site officiel Site de l'EATCS Site de l'EACSLSite de SIGLOG (ACM) modifier  Le prix Alonzo-Church est un prix annuel, aussi appelé « Alonzo Church Award for Outstanding Contributions to Logic and Comput...

 

Lorenzo Richelmy2017Lahir25 Maret 1990 (umur 34)La Spezia, ItaliaKebangsaanItaliaPekerjaanAktorDikenal atasMarco Polo Lorenzo Richelmy (lahir 25 Maret 1990) adalah aktor asal Italia, yang paling dikenal oleh penonton di luar Italia untuk penampilannya dalam seri asli Netflix Marco Polo. Sebelum berperan dalam serial tersebut, ia muncul di beberapa acara televisi dan film Italia. Ia menempuh pendidikan di Centro Sperimentale di Cinematografia, dan merupakan siswa termuda yang pernah masu...

 

Carcere di San VittoreEsterno del carcere nel 2021UbicazioneStato Italia CittàMilano IndirizzoPiazza Filangeri Coordinate45°27′42.97″N 9°09′56.48″E / 45.461937°N 9.165688°E45.461937; 9.165688Coordinate: 45°27′42.97″N 9°09′56.48″E / 45.461937°N 9.165688°E45.461937; 9.165688 Informazioni generaliTipocarcere voci di architetture militari presenti su Wikipedia Modifica dati su Wikidata · Manuale Il carcere di San Vittore è un is...

Antibiotic medication GentamicinClinical dataPronunciation/ˌdʒɛntəˈmaɪsən/ Trade namesCidomycin, Genticyn, Garamycin, othersAHFS/Drugs.comMonographMedlinePlusa682275License data US DailyMed: Gentamicin Pregnancycategory AU: D[1] Routes ofadministrationIntravenous, eye drop, Intramuscular injection, Topical administration, ear dropDrug classAminoglycoside antibioticATC codeD06AX07 (WHO) J01GB03 (WHO) S01AA11 (WHO) S02AA14 (WHO) S03AA0...

 

Chinese human rights activist (born 1950) In this Chinese name, the family name is Wei. Wei Jingsheng魏京生Wei at the European Parliament in Strasbourg on the 25th anniversary of the Sakharov Prize, 20 November 2013Born (1950-05-20) 20 May 1950 (age 73)Beijing, ChinaEducationHigh School Affiliated to Renmin University of ChinaOccupationsWriterhuman rights activistKnown forLeader of Democracy Wall MovementAwardsOlof Palme PrizeSakharov PrizeRobert F. Kennedy Human Rights Award Wei...

 

American politician (1879-1968) Jim Nance McCordMcCord, c. 191340th Governor of TennesseeIn officeJanuary 16, 1945 – January 16, 1949Preceded byPrentice CooperSucceeded byGordon BrowningMember of the U.S. House of Representatives from Tennessee's 5th districtIn officeJanuary 3, 1943 – January 3, 1945Preceded byPercy PriestSucceeded byHarold Earthman Personal detailsBorn(1879-03-17)March 17, 1879Unionville, TennesseeDiedSeptember 2, 1968(1968-09-02) (aged 89)Nash...

American editor and politician (1866–1945) Max HayesHayes in 1910BornMaximillian Sebastian Hayes(1866-05-25)May 25, 1866Havana, Ohio, USDiedOctober 11, 1945(1945-10-11) (aged 79)Cleveland, Ohio, USPolitical partyPopulist (1890–1896)Socialist Labor (1896–1899)Social Democratic (1899–1901)Socialist (1901–1919)Labor (1919–1920)Farmer–Labor (1920–1936) Maximillian Sebastian Hayes (25 May 1866 – 11 October 1945) was an American newspaper editor, trade union activist, and soc...

 

China Template‑class China portalThis template is within the scope of WikiProject China, a collaborative effort to improve the coverage of China related articles on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.ChinaWikipedia:WikiProject ChinaTemplate:WikiProject ChinaChina-related articlesTemplateThis template does not require a rating on Wikipedia's content assessment scale. Trains: Stations / Art...

 

British politician and peer The Right HonourableThe Earl of HalifaxPC KBAuditor of the ExchequerIn office1714–1739MonarchGeorge IIPreceded byThe Earl of HalifaxSucceeded byThe Lord WalpoleMember of Parliament for NorthamptonIn office1707–1715Serving with Francis Arundell, William WykesPreceded byParliament of EnglandSucceeded byWilliam WykesWilliam WilmerIn office1705–1707Serving with Francis ArundellPreceded bySir Matthew DudleyFrancis ArundellSucceeded byParliament...

Sporting event delegationCook Islands at theOlympicsFlag of the Cook IslandsIOC codeCOKNOCCook Islands Sports and National Olympic CommitteeWebsitewww.oceaniasport.com/cookisMedals Gold 0 Silver 0 Bronze 0 Total 0 Summer appearances1988199219962000200420082012201620202024 The Cook Islands has competed in eight Summer Olympic Games. It has never competed in the Winter Games. The Cook Islands has yet to win a medal as of 2020[update]. The Cook Islands is the only one of the associated ...

 

NaskahPapirus P {\displaystyle {\mathfrak {P}}} 5NamaP. Oxy. 208 + 1781TeksInjil Yohanes1; 16; 20 †Waktu~250Aksarabahasa YunaniDitemukanOxyrhynchus, MesirKini diBritish LibraryKutipanGrenfell & Hunt, Oxyrhynchus Papyri II, 1899, pp. 1 ff; XV, pp. 8-12.Ukuran12,5 cm kali 25 cmJenisTeks WesternKategoriITangantangan dokumentariCatatandekat dengan Codex Sinaiticus Papirus 5 (bahasa Inggris: Papyrus 5; dalam penomoran Gregory-Aland), diberi kode siglum P {\displaystyle {\m...

 

Pour les articles homonymes, voir Impact (homonymie). Cet article est une ébauche concernant une police de caractères. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. ImpactClassificationSystème Alphabet latinType Caractère de titrage, famille typographique (d)Vox-Atypi Linéale (d)HistoriquePays d'origine Royaume-UniFonderie Stephenson BlakeTypographe Geoffrey Lee (d)Création 1963modifier - modifier le cod...

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。 出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: バルディッシュ クロムフォードの住人たち – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL (2020年5月)このフィクショ�...

 

List of events ← 1764 1763 1762 1761 1760 1765 in Wales → 1766 1767 1768 1769 1770 Centuries: 16th 17th 18th 19th 20th Decades: 1740s 1750s 1760s 1770s 1780s See also:List of years in WalesTimeline of Welsh history 1765 in Great Britain Scotland Elsewhere Events from the year 1765 in Wales. Incumbents Lord Lieutenant of Anglesey – Sir Nicholas Bayly, 2nd Baronet[1][2][3][4] Lord Lieutenant of Brecknockshire and Lord Lieutenant of Monmouthshire �...