数据结构——队列基本操作的实现

顺序表实现循环列表

在数组中留出了一个空白格,用以区分列表满与列表空的情况。

#include<bits/stdc++.h>
using namespace std;
#define clr(a) memset(a, 0, sizeof(a))
#define line cout<<"----------"<<endl;

#define MAXSIZE 6
#define QElemType int
#define Status bool
#define OK 1
#define ERROR 0

typedef struct{
    QElemType *base;
    int Front;
    int rear;
}SqQueue;
SqQueue Q;
QElemType x;

Status InitQueue(SqQueue &Q){
    Q.base = new QElemType[MAXSIZE];
    if(!Q.base) exit(OVERFLOW);
    Q.Front = Q.rear = 0;
    return OK;
}

int QueueLength(SqQueue Q){
    return (Q.rear + MAXSIZE - Q.Front) % MAXSIZE;
}

Status 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;
}

Status 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];
    else return -1;
}

int main(){
    InitQueue(Q);
    printf("当前队列元素共 %d 个\n", QueueLength(Q));
    for(int i = 0; i < MAXSIZE; i++){
        EnQueue(Q, i+1);
        printf("当前队列元素共 %d 个,队首元素为:%d\n", QueueLength(Q), GetHead(Q));
    }
    while(QueueLength(Q) > 0){
        DeQueue(Q, x);
        printf("当前弹出元素 %d\n", x);
        printf("当前队列元素共 %d 个,队首元素为:%d\n", QueueLength(Q), GetHead(Q));
    }
    return 0;
}

链式队列

#include<bits/stdc++.h>
using namespace std;
#define clr(a) memset(a, 0, sizeof(a))
#define line cout<<"----------"<<endl;

#define MAXSIZE 6
#define QElemType int
#define Status bool
#define OK 1
#define ERROR 0

typedef struct QNode{
    QElemType data;
    struct QNode *next;
}QNode, *QueuePtr;

typedef struct{
    QueuePtr Front;
    QueuePtr rear;
}LinkQueue;
LinkQueue Q;
QNode *p;
QElemType x;

Status InitQueue(LinkQueue &Q){
    Q.Front = Q.rear = new QNode;
    Q.Front->next = NULL;
    return OK;
}

Status EnQueue(LinkQueue &Q, QElemType e){
    p = new QNode;
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    return OK;
}

Status DeQueue(LinkQueue &Q, QElemType &e){
    if(Q.Front == Q.rear) return ERROR;
    p = Q.Front->next;
    e = p->data;
    Q.Front->next = p->next;
    if(Q.rear == p) Q.rear = Q.Front;
    delete p;
    return OK;
}

QElemType GetHead(LinkQueue Q){
    if(Q.Front != Q.rear)
        return Q.Front->next->data;
    else return -1;
}

int main(){
    InitQueue(Q);
    for(int i = 0; i < MAXSIZE; i++){
        EnQueue(Q, i+1);
        printf("插入元素 %d\n", i+1);
    }
    printf("当前队首元素为%d\n", GetHead(Q));
    while(Q.Front != Q.rear){
        DeQueue(Q, x);
        printf("当前弹出元素 %d ,队首元素为:%d\n", x, GetHead(Q));
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值