搜尋此網誌

2025年12月16日星期二

Queues and Stacks

Queue (FIFO)

  • Definition: A queue is a linear data structure that follows the First In, First Out (FIFO) principle.
  • Analogy: Think of people lining up at a ticket counter. The first person to join the line is the first to be served.
#include <iostream>
#include <queue>
using namespace std;

int main() {
    queue<int> q;

    // Enqueue elements into the queue
    q.push(10);
    q.push(20);
    q.push(30);

    cout << "Queue (FIFO):" << endl;
    while (!q.empty()) {
        cout << q.front() << " ";  // Access the front element
        q.pop();                   // Remove the front element
    }
    return 0;
}

while (!q.empty())
q → This is your queue object (e.g., queue q;).
q.empty() → This function returns true if the queue has no elements, otherwise false.
!q.empty() → The ! (logical NOT) operator flips the result:
If the queue is not empty, !q.empty() is true.
If the queue is empty, !q.empty() is false.
while (!q.empty()) → This loop continues to run as long as the queue has elements inside.

Stack (LIFO)

  • Definition: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
  • Analogy: Imagine a stack of plates. The last plate placed on top is the first one you take off.
#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> s;

    // Push elements onto the stack
    s.push(10);
    s.push(20);
    s.push(30);

    cout << "Stack (LIFO):" << endl;
    while (!s.empty()) {
        cout << s.top() << " ";  // Access the top element
        s.pop();                 // Remove the top element
    }
    return 0;
}

Microsoft Copilot

沒有留言:

發佈留言