一、队列

数据结构学了有一阵子了,就自己模仿C++自带的队列写了一个链队,用法和C++的差不多,不足之处请指教。

#include <stdio.h>
#include <stdlib.h>
typedef int QElemType;//数据类型 
typedef struct QNode {
    QElemType data;
    struct QNode *next;
}*QueuePtr;
QueuePtr p;
struct LinkQueue {
    int length;//队列长度 
    QueuePtr head, tail;//头尾指针 
    LinkQueue() {//初始化 
        length = 0;
        head = tail = (QNode *)malloc(sizeof(QNode));
        head -> next = NULL;
    }
    void push(QElemType e) {//入队 
        length++;
        p = (QNode*)malloc(sizeof(QNode));
        p -> data = e;
        p -> next = NULL;
        tail -> next = p;
        tail = p;
    }
    void pop() {//出队 
        if (head != tail) {
            length--;
            p = head -> next;
            head -> next = p -> next;
            if (tail == p)
                tail = head;
            free(p);
        }
    }
    bool empty() {//判断队列是否为空 
        return !length;
    }
    void clear() {//清空队列 
        length = 0;
        while (head != tail) {
            p = head -> next;
            head -> next = p -> next;
            if (tail == p)
                tail = head;
            free(p);
        }
    }
    QElemType front() {//访问队首元素 
        if (head != tail)
            return head -> next -> data;
    }
    QElemType back() {//访问队尾元素 
        if (head != tail)
            return tail -> data;
    }
    int size() {//返回队列长度 
        return length;
    }
};
int main() {
    LinkQueue Q;
    Q.push(3);
    Q.push(2);
    Q.push(5);
    Q.push(6);
    Q.push(9);
    printf("队列的长度:%d\n", Q.size());
    printf("队列中的元素:");
    while (!Q.empty()) {
        printf("%d ", Q.front());
        Q.pop();
    }
    return 0; 
}

未完待续。。。