佇列——以陣列Q[m]存放迴圈佇列元素,設定一個標誌tag,以tag=0和tag=1來區別在頭指標和尾指標相等時,佇列為空或滿
阿新 • • 發佈:2020-11-20
特別用了指標來計算
但如果是int*a = new int; *a = 1; 直接用*a去進行運算,就跟正常的佇列設計是一樣的了
所以感覺用指標a而不是整形*a,有點多餘,感覺是誤解了
#include<iostream> using namespace std; #define QElemType int #define MAXSIZE 100 /* 以陣列Q[m]存放迴圈佇列元素,設定一個標誌tag,以tag=0和tag=1來區別在頭指標和尾指標相等時,佇列為空或滿 */ typedef struct { QElemType *base; int *front;int *front1; int *rear; int tag; }SqQueue; string InitQueue(SqQueue &Q){ Q.base = new QElemType[MAXSIZE]; Q.front = Q.rear = Q.front1+1; Q.tag = 0; //tag=0 佇列為空 return "OK"; } int QueueLength(SqQueue Q){ return (Q.rear - Q.front +MAXSIZE)%MAXSIZE; }string EnQueue(SqQueue &Q,QElemType e){ if(Q.tag == 1) return "Queue is full"; Q.base[(Q.rear-Q.front1)-1] = e; if(Q.rear-Q.front1 == MAXSIZE) Q.rear = Q.front1+1; else Q.rear = Q.rear+1; Q.tag = 3; //佇列非空也非滿 if(Q.rear == Q.front) Q.tag = 1; //增加元素時,若頭尾指標相等,則表示佇列滿 return "OK"; } string DeQueue(SqQueue &Q,QElemType &e){ if(!Q.tag) return "ERROR"; e = Q.base[Q.front-Q.front1-1]; if(Q.front-Q.front1 == MAXSIZE) Q.front = Q.front1+1; else Q.front = Q.front+1; if(Q.rear == Q.front) Q.tag = 0; //刪除元素時,若頭尾指標相等,則表示佇列空 return "OK"; } int main(){ SqQueue Q; InitQueue(Q); cout << EnQueue(Q,2)<<endl; cout << EnQueue(Q,3)<<endl; QElemType e; cout << DeQueue(Q,e) << endl; cout << e<<endl; cout << DeQueue(Q,e) << endl; cout << e<<endl; cout << DeQueue(Q,e) << endl; system("pause"); return 0; }
用*a去設計(沒有加入tag來進行修改)
#include<iostream> using namespace std; #define QElemType int #define MAXSIZE 100 typedef struct { QElemType *base; int front; int rear; }SqQueue; string InitStack(SqQueue &Q){ Q.base = new QElemType[MAXSIZE]; Q.front = Q.rear = 0; return "OK"; } int QueueLength(SqQueue Q){ return (Q.rear - Q.front +MAXSIZE)%MAXSIZE; } string EnQueue(SqQueue &Q,QElemType e){ if((Q.rear+1)%MAXSIZE == Q.front) return "ERROR"; Q.base[Q.rear] = e; Q.rear = (Q.rear+1) % MAXSIZE; return "OK"; } string DeQueue(SqQueue &Q,QElemType &e){ if(Q.front==Q.rear) return "ERROR"; e = Q.base[Q.front]; Q.front = (Q.front+1) % MAXSIZE; return "OK"; } QElemType GetHead(SqQueue Q){ if(Q.front!=Q.rear) return Q.base[Q.front]; }