//【數據結構】用C++編寫隊列及基本操作(包括插入,出隊列,摧毀,清空等等) //頭文件 #ifndef _SEQ_STACK_ #define _SEQ_STACK_ #includeusing namespace std; template class Queue { public: Queue(size_t sz = INIT_SIZE) { capacity = sz > INIT_SIZE ? sz : INIT_SIZE; base = new Type[capacity]; front = back = 0; } ~Queue() { destory(); } public: bool empty() const //判斷是否為空 { return(front==back); } bool full()const //判斷是否已滿 { return((back+1)%capacity==front); } public: void push(const Type &x) //進隊列 { if (full()) { cout << "隊列已滿,不能插入。" << endl; return; } base[back] = x; back = (back + 1) % capacity; } void pop() //出隊列 { if (empty()) { cout << "隊列為空" << endl; return; } front=(front+1)%capacity; } bool getFront(Type &x) const //獲得隊列頭部 { if (empty()) { cout << "隊列為空" << endl; return false; } else { x = base[front]; return true; } } int length() const //求大小 { return back-front; } void clear() //清除 { front=back=0; } void destory() //摧毀 { delete[]base; base = NULL; capacity = front = back = 0; } void show() const //顯示 { if (empty()) { cout << "隊列為空" << endl; return; } for (int i = front; i != back; i = (i + 1) % capacity) { cout << base[i] << endl; } } void quit_system(int &x) { x = 0; } private: enum { INIT_SIZE = 8 }; Type *base; int capacity; int front; int back; }; #endif //主函數 #include "Queue.h" void main() { Queue myqueue; int select = 1; int Item; while (select) { cout << "***************************************" << endl; cout << "* [1] show [2] push *" << endl; cout << "* [3] pop [4] length *" << endl; cout << "* [5] clear [6] destory *" << endl; cout << "* [7] getFront [8] quit_system *" << endl; cout << "***************************************" << endl; cout << "請選擇:>"; cin >> select; switch (select) { case 1: myqueue.show(); break; case 2: cout << "請輸入要插入的值(-1結束):>"; while (cin >> Item, Item != -1) { myqueue.push(Item); } break; case 3: myqueue.pop(); break; case 4: cout << "大小為:" << myqueue.length() << endl; break; case 5: myqueue.clear(); break; case 6: myqueue.destory(); break; case 7: if (myqueue.getFront(Item)) cout << "頭元素為:"<