佇列的順序儲存結構
#include<iostream> using namespace std;
#define MAXSIZE 20
typedef int ElemType;
typedef struct { ElemType data[MAXSIZE]; int front; /* 頭指標 */ int rear; /* 尾指標,若佇列不空,指向佇列尾元素的下一個位置 */ int count; //元素個數 } SqQueue;
bool InitQueue(SqQueue &Sq) { cout << "Init Queue ..." << endl; Sq.front = 0; Sq.rear = 0; Sq.count = 0; return true; }
bool ClearQueue(SqQueue &Sq) { cout << "Clear Queue ..." << endl; Sq.front = 0; Sq.rear = 0; Sq.count = 0; return true; }
bool QueueEmpty(SqQueue &Sq) { return Sq.count == 0; /* 佇列空的標誌 */ }
bool QueueFull(SqQueue &Sq) { return Sq.count == MAXSIZE; }
int QueueLength(SqQueue &Sq) { if (QueueFull(Sq)) return MAXSIZE;
/* 佇列的當前長度 */ return (Sq.rear - Sq.front + MAXSIZE) % MAXSIZE; } /* 返回頭元素 */ bool GetHead(SqQueue &Sq, ElemType *pe) { if (QueueEmpty(Sq)) return false; else { *pe = Sq.data[Sq.front]; cout << "Get Head Item " << *pe << endl; return true; } }
bool EnQueue(SqQueue &Sq, ElemType Elem) { /* 佇列滿 */ if (QueueLength(Sq) == MAXSIZE) return false; cout << "EnQueue Item " << Elem << endl; Sq.data[Sq.rear] = Elem;/* 將元素賦值給隊尾 */ Sq.rear = (Sq.rear + 1) % MAXSIZE;/* rear指標向後移一位置, */ /* 若到最後則轉到陣列頭部 */ Sq.count++; return true; }
bool DeQueue(SqQueue &Sq, ElemType *pe) { if (QueueEmpty(Sq)) return false; *pe = Sq.data[Sq.front];/* 將隊頭元素賦值給*pe */ cout << "DeQueue Item " << *pe << endl; Sq.front = (Sq.front + 1) % MAXSIZE;/* front指標向後移一位置, */ /* 若到最後則轉到陣列頭部 */
Sq.count--; return true; }
bool QueueTraverse(SqQueue &Sq) { if (QueueEmpty(Sq)) { cout << "Queue is empty" << endl; return false; }
cout << "Queue Traverse ..." << endl; for (int i = 0; i < Sq.count; i++) cout << Sq.data[i + Sq.front] << ' '; cout << endl; return true; }
int main(void) { SqQueue Sq; InitQueue(Sq); for (int i = 0; i < 20; i++) EnQueue(Sq, i); QueueTraverse(Sq); if (!QueueEmpty(Sq)) cout << "Queue Length: " << QueueLength(Sq) << endl; int result; GetHead(Sq, &result); DeQueue(Sq, &result); DeQueue(Sq, &result); if (!QueueEmpty(Sq)) cout << "Queue Length: " << QueueLength(Sq) << endl; QueueTraverse(Sq);
return 0; }