首页 > 其他 > 详细

数据结构--队列

时间:2021-04-11 23:36:47      阅读:25      评论:0      收藏:0      [点我收藏+]

队列的概念

队列 : 只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,

队列具有  先进先出  原则.

入队列 : 进行插入操作的一端称为队尾.

出队列 : 进行删除操作的一端称为对头.                                             

 

  队列的实现        (常用实现队列 : 含有尾指针的单链表) 

  顺序表 :

     入队列 :   push ---> 从队尾存入元素

              表尾 ---> 队尾 : 尾插 O(1)   

    出队列 :   pop ---> 从队头取出元素                                                                  

              表头 ---> 队头 : 头删  O(n)

 

链表 : 双向带头循环链表 (含有尾指针的单链表,尾插O(1),头删O(1);效率较高)      

     入队列 :   push ---> 从队尾存入元素                                                                                   

              表尾 ---> 队尾 : 尾插  O(n)

    出队列 :   pop ---> 从队头取出元素                                                                                       

              表头 ---> 队头 : 头删  O(1)

 

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

typedef int QDataType;

typedef struct QNode{
    struct QNode* _next;
    QDataType _data;
}QNode;

typedef struct Queue{
    QNode* _front;
    QNode* _rear;
}Queue;

//初始化空队列
void queueInit(Queue* q){
    q->_front = q->_rear = NULL;
}

//检查容量
QNode* creatNode(QDataType data){
    QNode* node = (QNode*)malloc(sizeof(QNode));
    node->_data = data;
    node->_next = NULL;
    return node;
}

//队尾入队/尾插
void queuePush(Queue* q, QDataType data){
    QNode* node = creatNode(data);
    //空队列
    if (q->_front == NULL)
        q->_front = q->_rear = node;
    else{
        q->_rear->_next = node;
        q->_rear = node;
    }
}

//队头出队/头删
void queuePop(Queue* q){
    if (q->_front){
        QNode* next = q->_front->_next;
        free(q->_front);
        q->_front = next;
        //删除之后是否为空表
        if (q->_front == NULL){
            q->_rear = NULL;
        }
    }
}

//获取队头元素
QDataType queueFront(Queue* q){
    return q->_front->_data;
}

//获取队尾元素
QDataType queueBack(Queue* q){
    return q->_rear->_data;
}

//队列是否为空
int queueEmpty(Queue* q){
    if (q->_front == NULL)
        return 1;
    return 0;
}

//销毁队列
void queueDestory(Queue* q){
    QNode* cur = q->_front;
    while (cur){
        QNode* next = cur->_next;
        free(cur);
        cur = next;
    }
    q->_front = q->_rear = NULL;
}

 void test(){
    Queue q;
    queueInit(&q);
    queuePush(&q, 1);
    queuePush(&q, 2);
    queuePush(&q, 3);
    queuePush(&q, 4);

    //打印队列
    while (queueEmpty(&q) != 1){
        printf("%d  ", queueFront(&q));
        queuePop(&q);
    }
    printf("\n");

    queuePop(&q);
    queuePop(&q);
    queuePop(&q);
    queuePop(&q);

    while (queueEmpty(&q) != 1){
        printf("%d  ", queueFront(&q));
        queuePop(&q);
    }
    printf("\n");
}

int main(){
    test();
    system("pause");
    return 0;
}

 

数据结构--队列

原文:https://www.cnblogs.com/enjoyC/p/14642559.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!