队列

#include "stdafx.h"
#include<iostream>

using namespace std;
typedef int QElenType;
typedef struct QNode {
    QElenType data;
    struct QNode * next;
}QNode,*QNodePtr;

typedef struct {
    QNodePtr front;
    QNodePtr rear;
}LinkQueue;

typedef enum Status {
    success, fail, fatal, rangeerror, overflow
}Status;

Status InitQueue(LinkQueue &q) {
    q.front = q.rear = (QNodePtr)malloc(sizeof(QNode));
    if (!q.front) exit(OVERFLOW);
    q.rear->next = NULL;
    return success;
}

Status DestoryQueue(LinkQueue &q) {
    while (q.front) {
        q.rear = q.front->next;
        free(q.front);
        q.front = q.rear;
    }
    return success;
}

Status EnQueue(LinkQueue &q, QElenType elem) {
    QNodePtr p = (QNodePtr)malloc(sizeof(QNode));
    if (!p) exit(OVERFLOW);
    p->data = elem; p->next = NULL;
    q.rear->next = p;
    q.rear = p;
    return success;
}

Status DeQueue(LinkQueue &q, QElenType &elem) {
    if (q.front == q.rear) return fail;
    QNodePtr p = q.front->next;
    elem = p->data;
    q.front->next = p->next;
    if (q.front == q.rear) q.rear = q.front;
    free(p);
    return success;
}

void PrintQueue(LinkQueue &q) {
    QNodePtr p;
    p = q.front->next;
    while (p) {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
}

int main() {
    LinkQueue q;
    int a[] = { 2,4,6,9 };
    int len = sizeof(a) / sizeof(a[0]);
    InitQueue(q);
    for (int i = 0; i < len - 1; i++) {
        EnQueue(q, a[i]);
    }
    PrintQueue(q);
    QElenType elem;
    DeQueue(q, elem);
    PrintQueue(q);
    DestoryQueue(q);
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/linkmust/p/10925356.html