1. 程式人生 > >數據結構C語言版-隊列

數據結構C語言版-隊列

tdi out size != name thead h+ clas def

#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace std;

typedef int QElemType;

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

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

bool InitQueue(LinkQueue &Q);

bool DestoryQueue(LinkQueue &Q);

bool ClearQueue(LinkQueue &Q);

bool QueueEmpty(LinkQueue Q);

int QueueLength(LinkQueue Q);

int GetHead(LinkQueue Q);

bool EnQueue(LinkQueue &Q, QElemType e);

bool DeQueue(LinkQueue &Q, QElemType &e);

void QueueTraverse(LinkQueue Q);

//Q.front裏面是沒有數據的
//Q.rear裏面是有數據的
int main() {
    LinkQueue s;
    InitQueue(s);
    EnQueue(s, 5);
    EnQueue(s, 6);
    EnQueue(s, 7);
    ClearQueue(s);
    EnQueue(s, 8);
    EnQueue(s, 100);
    cout << QueueLength(s) << endl;
    int a;
    DeQueue(s, a);
    cout << a << endl;
    if (QueueEmpty(s)) {
        cout << ‘a‘ << endl;
    }
    cout << GetHead(s) << endl;
}

void QueueTraverse(LinkQueue Q) {
    if (Q.front == Q.rear) {
        return;
    }
    QueuePtr tmp = Q.front->next;
    while (tmp != Q.rear) {
        printf("%d ", tmp->data);
        tmp = tmp->next;
    }
    printf("%d\n", tmp->data);
}


int GetHead(LinkQueue Q) {
    return Q.front->next->data;
}

bool QueueEmpty(LinkQueue Q) {
    if (Q.front == Q.rear) {
        return true;
    }
    return false;
}

int QueueLength(LinkQueue Q) {
    int length = 0;
    LinkQueue tmp = Q;
    while (tmp.front) {
        length++;
        tmp.front = tmp.front->next;
    }
    return length - 1;
}


bool InitQueue(LinkQueue &Q) {
    Q.front = Q.rear = (QNode *) malloc(sizeof(QNode));
    if (!Q.front) {
        exit(EOVERFLOW);
    }
    Q.front->next = NULL;
    return true;
}

bool ClearQueue(LinkQueue &Q) {
    QueuePtr tmp = Q.front->next;
    while (tmp) {
        QueuePtr tp = tmp;
        tmp = tmp->next;
        free(tp);
    }
    Q.rear = Q.front;
    Q.front->next = NULL;
}

bool DestoryQueue(LinkQueue &Q) {
    while (Q.front) {
        Q.rear = Q.front->next;
        free(Q.front);
        Q.front = Q.rear;
    }
    return true;
}

bool EnQueue(LinkQueue &Q, QElemType e) {
    QueuePtr p = (QueuePtr) malloc(sizeof(QNode));
    if (!p) {
        exit(EOVERFLOW);
    }
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    return true;
}


bool DeQueue(LinkQueue &Q, QElemType &e) {
    if (Q.front == Q.rear) {
        return false;
    }
    QueuePtr p = Q.front->next;
    e = p->data;
    Q.front->next = p->next;
    if (Q.rear == p) {
        Q.rear = Q.front;
    }
    free(p);
    return true;
}

數據結構C語言版-隊列