搜尋
首頁web前端js教程了解佇列資料結構:掌握 JavaScript 中的 FIFO 原理

Understanding Queues Data Structure: Mastering FIFO Principle in JavaScript

Gambar ini... ? Bayangkan anda berada di kedai kopi yang sibuk pada waktu pagi ☕️. Semasa anda masuk, anda melihat barisan panjang pelanggan yang mengidam kafein menunggu untuk membuat pesanan mereka. Barista, bekerja dengan cekap di belakang kaunter, mengambil dan menyediakan pesanan dalam urutan yang tepat bahawa orang menyertai barisan. Senario harian ini dengan sempurna menggambarkan konsep Baris Gilir sebagai struktur data.

Dalam dunia pengaturcaraan, Queue ialah struktur data asas yang mematuhi prinsip First In, First Out (FIFO). Sama seperti barisan kedai kopi, orang pertama yang menyertai barisan adalah yang pertama dihidangkan dan meninggalkannya ?. Konsep mudah tetapi berkuasa ini mempunyai aplikasi yang meluas dalam pelbagai bidang sains komputer dan pembangunan perisian, daripada mengurus kerja cetakan ?️ dan mengendalikan permintaan rangkaian ? untuk melaksanakan algoritma carian luas pertama dan menyelaraskan penjadualan tugas dalam sistem pengendalian ?.

Dalam artikel khusus ini, kami akan meneroka dunia Gilir yang menarik, menyelidiki kerja dalaman, pelaksanaan dan aplikasi praktikalnya dalam JavaScript ?. Sama ada anda baru dalam pengekodan atau pengaturcara pertengahan yang ingin memperdalam pemahaman anda, tutorial ini akan memberikan anda pengetahuan dan kemahiran untuk menggunakan struktur data Baris Gilir dengan berkesan dalam projek anda ?️.

Jadual Kandungan

  1. Apakah itu Baris?
  2. Istilah Utama
  3. Jenis Baris
  4. Operasi Beratur
  5. Aplikasi Baris Gilir Dunia Sebenar
  6. Pelaksanaan Baris Gilir dalam JavaScript
  7. Kesimpulan


Apakah itu Queue?

Baris Gilir ialah struktur data linear yang mengikut prinsip Masuk Pertama, Keluar Dahulu (FIFO). Ia boleh digambarkan sebagai barisan orang yang menunggu perkhidmatan, di mana orang yang tiba dahulu dilayan dahulu. Dari segi pengaturcaraan, ini bermakna elemen pertama yang ditambahkan pada baris gilir akan menjadi elemen pertama yang akan dialih keluar.

Terminologi Utama

Sebelum kita mendalami Baris Gilir, mari biasakan diri kita dengan beberapa istilah penting:

Term Description
Enqueue The process of adding an element to the rear (end) of the queue.
Dequeue The process of removing an element from the front of the queue.
Front The first element in the queue, which will be the next to be removed.
Rear The last element in the queue, where new elements are added.
IsEmpty A condition that checks if the queue has no elements.
Size The number of elements currently in the queue.

Types of Queues

While we'll primarily focus on the basic Queue implementation, it's worth noting that there are several types of Queues:

  1. Simple Queue: The standard FIFO queue we'll be implementing.
  2. Circular Queue: A queue where the rear is connected to the front, forming a circle. This is more memory efficient for fixed-size queues.
  3. Priority Queue: A queue where elements have associated priorities, and higher priority elements are dequeued before lower priority ones.

Queue Operations

The main operations performed on a Queue are:

  1. Enqueue: Add an element to the rear of the queue.
  2. Dequeue: Remove and return the element at the front of the queue.
  3. Peek: Return the element at the front of the queue without removing it.
  4. IsEmpty: Check if the queue is empty.
  5. Size: Get the number of elements in the queue.

Real-World Applications of Queues

Queues have numerous practical applications in computer science and software development:

  1. Task Scheduling: Operating systems use queues to manage processes and tasks.
  2. Breadth-First Search (BFS): In graph algorithms, queues are used to explore nodes level by level.
  3. Print Job Spooling: Printer queues manage the order of print jobs.
  4. Keyboard Buffer: Queues store keystrokes in the order they were pressed.
  5. Web Servers: Request queues help manage incoming HTTP requests.
  6. Asynchronous Data Transfer: Queues in messaging systems ensure data is processed in the correct order.

Queue Implementation in JavaScript

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Queue {
  constructor() {
    this.front = null;
    this.rear = null;
    this.size = 0;
  }

  // Add an element to the rear of the queue
  enqueue(value) {
    const newNode = new Node(value);
    if (this.isEmpty()) {
      this.front = newNode;
      this.rear = newNode;
    } else {
      this.rear.next = newNode;
      this.rear = newNode;
    }
    this.size++;
  }

  // Remove and return the element at the front of the queue
  dequeue() {
    if (this.isEmpty()) {
      return "Queue is empty";
    }
    const removedValue = this.front.value;
    this.front = this.front.next;
    this.size--;
    if (this.isEmpty()) {
      this.rear = null;
    }
    return removedValue;
  }

  // Return the element at the front of the queue without removing it
  peek() {
    if (this.isEmpty()) {
      return "Queue is empty";
    }
    return this.front.value;
  }

  // Check if the queue is empty
  isEmpty() {
    return this.size === 0;
  }

  // Return the number of elements in the queue
  getSize() {
    return this.size;
  }

  // Print the elements of the queue
  print() {
    if (this.isEmpty()) {
      console.log("Queue is empty");
      return;
    }
    let current = this.front;
    let queueString = "";
    while (current) {
      queueString += current.value + " -> ";
      current = current.next;
    }
    console.log(queueString.slice(0, -4)); // Remove the last " -> "
  }
}

// Usage example
const queue = new Queue();

queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

console.log("Queue after enqueuing 10, 20, and 30:");
queue.print(); // Output: 10 -> 20 -> 30

console.log("Front element:", queue.peek()); // Output: 10

console.log("Dequeued element:", queue.dequeue()); // Output: 10

console.log("Queue after dequeuing:");
queue.print(); // Output: 20 -> 30

console.log("Queue size:", queue.getSize()); // Output: 2

console.log("Is queue empty?", queue.isEmpty()); // Output: false

queue.enqueue(40);
console.log("Queue after enqueuing 40:");
queue.print(); // Output: 20 -> 30 -> 40

while (!queue.isEmpty()) {
  console.log("Dequeued:", queue.dequeue());
}

console.log("Is queue empty?", queue.isEmpty()); // Output: true

Conclusion

Congratulations! You've now mastered the Queue data structure in JavaScript. From understanding its basic principles to implementing various types of queues and solving LeetCode problems, you've gained a solid foundation in this essential computer science concept.

Queues are not just theoretical constructs; they have numerous real-world applications in software development, from managing asynchronous tasks to optimizing data flow in complex systems. As you continue your programming journey, you'll find that a deep understanding of queues will help you design more efficient algorithms and build more robust applications.

To further solidify your knowledge, I encourage you to practice more Queue-related problems on LeetCode and other coding platforms



Stay Updated and Connected

To ensure you don't miss any part of this series and to connect with me for more in-depth discussions on Software Development (Web, Server, Mobile or Scraping / Automation), data structures and algorithms, and other exciting tech topics, follow me on:

  • GitHub
  • Linkedin
  • X (Twitter)

Stay tuned and happy coding ?‍??

以上是了解佇列資料結構:掌握 JavaScript 中的 FIFO 原理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中