# 第一種 ```C++= #include <iostream> using namespace std; const int MAX_SIZE = 5; class CircularQueue { private: int front, rear; int queue[MAX_SIZE]; public: CircularQueue() { front = rear = -1; } bool isEmpty() { return front == -1; } bool isFull() { return (front == 0 && rear == MAX_SIZE - 1) || (rear == (front - 1) % (MAX_SIZE - 1)); } void enqueue(int value) { if (isFull()) { cout << "[佇列已滿,中斷程式]" << endl; exit(0); } if (isEmpty()) front = rear = 0; else rear = (rear + 1) % MAX_SIZE; cout << "請輸入一個值以存入佇列,欲取出值請輸入-2,(結束請輸入-1)" << endl; // 修改提示訊息 queue[rear] = value; cout << "加入佇列值[" << value << "]" << endl; } void dequeue() { if (isEmpty()) { cout << "[佇列已經空了]" << endl; exit(0); } cout << "取出佇列值[" << queue[front] << "]" << endl; queue[front] = 0; if (front == rear) front = rear = -1; else front = (front + 1) % MAX_SIZE; } void display() { if (isEmpty()) { cout << "[佇列已經空了]" << endl; return; } int i = front; do { cout << "[" << queue[i] << "]"; i = (i + 1) % MAX_SIZE; } while (i != (rear + 1) % MAX_SIZE); cout << endl; } }; int main() { CircularQueue cq; int choice, value; do { cout << "請輸入一個值以存入佇列,欲取出值請輸入-2,(結束請輸入-1)\n請選擇操作: "; cin >> choice; switch (choice) { case -1: cout << "程式結束" << endl; cq.display(); break; case -2: cq.dequeue(); break; default: cq.enqueue(choice); break; } } while (choice != -1); return 0; } ``` # 第二種改老師的的? ```C++= #include <iostream> using namespace std; const int SIZE = 5; int main() { int front, rear, val = 0, queue[SIZE] = {0}; front = rear = -1; while (true) { cout << "請輸入一個值以存入佇列,欲取出值請輸入-2,(結束請輸入-1): "; cin >> val; if (val == -1) { cout << "程式結束。" << endl; break; } else if (val == -2) // 取出值 { if (front == -1) { cout << "[佇列已經空了]" << endl; break; } cout << "取出佇列值[" << queue[front] << "]" << endl; if (front == rear) { front = rear = -1; // 重置表示對列已空 } else { front = (front + 1) % SIZE; // 循環對列的前進 } } else { if ((rear + 1) % SIZE == front) { cout << "[佇列已經滿了]" << endl; } else { if (front == -1) { front = 0; } rear = (rear + 1) % SIZE; queue[rear] = val; } } } // 輸出對列中剩餘的數據 cout << "\n佇列剩餘資料:" << endl; if (front == -1) { cout << "佇列已經空了" << endl; } else { int current = front; do { cout << "[" << queue[current] << "]"; current = (current + 1) % SIZE; } while (current != (rear + 1) % SIZE); } cout << endl; return 0; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up