数据结构 - 自写链式队列

42 篇文章 28 订阅
15 篇文章 1 订阅

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

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ityanger

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值