隊列——以數組Q[m]存放循環隊列元素,設置一個標志tag,以tag=0和tag=1來區別在頭指針和尾指針相等時,隊列為空或滿


 

特別用了指針來計算

但如果是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];
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM