首頁 > web前端 > js教程 > 主體

了解佇列資料結構:掌握 JavaScript 中的 FIFO 原理

Mary-Kate Olsen
發布: 2024-10-10 08:23:29
原創
786 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板