数据结构 - 自写链式队列(未完待续。。。)

一、队列

数据结构学了有一阵子了,就自己模仿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; 
}

未完待续。。。

全部评论

相关推荐

10-28 17:30
已编辑
华东交通大学 Java
想进开水团喝开水:字节的hr的本职工作就是黄金矿工
秋招笔试记录
点赞 评论 收藏
分享
11-13 20:16
已编辑
厦门理工学院 软件测试
专业嗎喽:硕佬,把学校背景放后面几段,学校背景双非还学院,让人看了就不想往下看。 把实习经历和个人奖项放前面,用数字化简述自己实习的成果和掌握的技能,比如负责项目一次通过率90%,曾4次发现项目潜在问题风险为公司减少损失等等
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务