队列的基本操作(简单版)

队列的基本操作(简单版)

参考了《大话数据结构》和严蔚敏的《数据结构(C语言版)》。

/*----------以下为队列的基本操作函数----------*/

/*初始化一个空队列*/
Status InitQueue(SqQueue *Q){
    if(!Q)return ERROR;             //若空间分配失败,则返回ERROR
    Q->front = 0;
    Q->rear = 0;
    return OK;
}

/*销毁队列*/
Status DestroyQueue(SqQueue *Q){
    free(Q);
    if(Q)return ERROR;              //若队列仍存在,则销毁失败,返回ERROR
    return OK;
}

/*将SqQueue清空为空队列*/
Status ClearQueue(SqQueue *Q){
    Q->front = 0;
    Q->rear = Q->front;
    if(Q->rear != Q->front)return ERROR;        //若尾指针未指向了头指针,则返回ERROR
    return OK;
}

/*判断SqQueue是否为空*/
Status IsQueueEmpty(SqQueue Q){
    if(Q.rear == Q.front)return TRUE;           //若尾指针指向头指针,则为空队列,返回TRUE
    else{ return FALSE;}                        //否则返回FALSE     
}

/*返回Q的元素个数,即队列长度*/
int QueueLength(SqQueue Q){
    int length = (Q.rear - Q.front + MAXSIZE) % MAXSIZE;    
    return length;
}

/*若队列不空,则用e返回队头元素,并返回OK;否则返回ERROR*/
Status GetHead(SqQueue Q, QElemType *e){
    if(Q.rear != Q.front){          //判断队列是否为空
        *e = Q.data[Q.front];
        return OK;
    }else{return ERROR;}
}

/*插入元素e为新的队尾元素*/
Status EnQueue(SqQueue *Q, QElemType e){
    if((Q->rear + 1) % MAXSIZE == Q->front)return ERROR;    // 若队列已满,则返回ERROR
    Q->data[Q->rear] = e;           //e 入队列
    Q->rear = (Q->rear + 1) % MAXSIZE;                      //队尾指针后移
    return OK;
}

/*若队列不空,则删除队头元素,并用e返回其值*/
Status DeQueue(SqQueue *Q, QElemType *e){
    if(Q->front == Q->rear)return ERROR;    //若队列为空,则返回ERROR
    *e = Q->data[Q->front];                 //若队列不为空,用e接收队头元素
    Q->front = (Q->front + 1) % MAXSIZE;        //队头指针后移
    return OK;
}

/*从队头到队尾进行遍历*/
Status QueueTraverse(SqQueue Q){
    int i = Q.front;
    for(i; i <= Q.rear; i ++){
        if(Q.data[i]){                      //若访问到该位置上的元素,则对其进行输出
            printf("%d\n", Q.data[i]);
        }else{
            return FALSE;                   //否则返回FALSE
        }
    }
    return OK;
}

猜你喜欢

转载自blog.csdn.net/li827437709/article/details/78393541