队列——以数组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];
}

 

posted @ 2020-11-20 16:14  倔强的不死人  阅读(1710)  评论(0编辑  收藏  举报