zoukankan      html  css  js  c++  java
  • C语言---队列(链表实现)

    队列的基本概念
    队列 (Queue) :也是运算受限的线性表。是一种先进先出 (First In First Out ,简称 FIFO) 的线性表。只允许在表的一端进行插入,而在另一端进行删除。
    队首 (front) :允许进行删除的一端称为队首。
    队尾 (rear) :允许进行插入的一端称为队尾。

    #include<stdio.h>
    #include<stdlib.h>
    #define ElementType int
    #define ERROR -99
    
    //构建结点信息 
    typedef struct Node{
        ElementType data;
        struct Node *next;
    }QNode;
    //构建节点头和尾指针,在队列的的增加和删除操作分别在尾和头部执行
     
    typedef struct {
        QNode *front;
        QNode *rear;
    }Queue;
    
    Queue* CreateQueue(){
    //申请结点内存,成功返回大于零的值,否则返回NULL 
        Queue* q = (Queue *)malloc(sizeof(Queue));
        if(!q){
            printf("内存空间不足
    ");
            return NULL;
        }
    //指针初值为NULL 
        q->front = q->rear = NULL;
        return q;
    }
    
    void AddQ(Queue *q,ElementType item){
        QNode* qNode=(QNode*)malloc(sizeof(QNode));
        if(!qNode){
            printf("内存空间不足
    ");
            exit(-1);
        }
        qNode->data = item;
        qNode->next = NULL;
        if(q->front==NULL){
            q->front = qNode;
        }
        if(q->rear == NULL){
            q->rear = qNode;
        }
        else{
    //头尾不为null,则执行下列操作
    //连上上一个指针 
            q->rear->next=qNode;
    //队尾指针从新被定义 
            q->rear=qNode;
        }
    }
    
    int IsEmptyQ(Queue* q){
        return (q->front == NULL);
    }
    
    ElementType DeleteQ(Queue* q){
        int item;
        if(IsEmptyQ(q)){
            printf("空队列
    ");
            return ERROR;
        }
        QNode *temp = q->front;
        if(q->rear == q->front){
            q->rear=NULL;
            q->front=NULL;
        }
        else{
    //在队列头指针进行操作 
            q->front = q->front->next;
        }
        item = temp->data;
        free(temp);
        return item;
    }
    
    void PrientQueue(Queue *q){
        if(IsEmptyQ(q)){
            printf("空队列
    ");
            return ;
        }
        printf("打印队列所有元素:
    ");
        QNode *qnode = q->front;
        while(qnode != NULL){
            printf("%d",qnode->data);
            qnode= qnode->next;
        }
        printf("
    ");
    }
    
    int main(){
        Queue *q = CreateQueue();
        AddQ(q,1);
        AddQ(q,2);
        AddQ(q,3);
        AddQ(q,4);
        PrientQueue(q);
        
        DeleteQ(q);
        DeleteQ(q);
        PrientQueue(q);
        
        return 0;
    }

    运行结果图

    非学无以广才,非志无以成学。 正是因为今天的不完美,才对未来充满希望。 ----长帆
  • 相关阅读:
    CodeForces 459D Pashmak and Parmida's problem
    cf 459c Pashmak and Buses
    hdu 1006 Tick and Tick 有技巧的暴力
    hdu 1005 Number Sequence
    hdu 1004 Let the Balloon Rise
    c++ 单引号和双引号
    c++一些总结
    剑指offer23 从上往下打印二叉树
    E: Unable to locate package
    vector
  • 原文地址:https://www.cnblogs.com/changfan/p/11737466.html
Copyright © 2011-2022 走看看