• 数据结构之队列


    #include  "stdafx.h"
    #include<iostream>
    using namespace std;
    #include<malloc.h>
    
    typedef int ElemType;
    #define OK               1        //正确
    #define ERROR            0        //失败
    typedef struct QNode
    {
    
        ElemType data;    //数据域
        QNode *next;    //下个节点指针域
    }QNode,*QNodePtr;
    
    typedef struct{
        QNodePtr front;
        QNodePtr rear; //指向队列最后一个元素
    }LinkQueue;
    //初始化
    void InitQueue(LinkQueue &q)
    {    
        q.front = (QNodePtr)malloc(sizeof(QNode)); //创建队列节点
        q.rear=q.front;
        if(!q.front) return;
        q.front->next=NULL;    //将队列的头指针的next设置为NULL,表示队列为空
    }
    //入队列,在队尾进行插入,再移动队尾指针
    void InsertQueue(LinkQueue &q,ElemType e)
    {    QNodePtr p;
        p = (QNodePtr)malloc(sizeof(QNode)); //创建队列节点
        if(!p) return;
        p->data=e;
        p->next=NULL;
        q.rear->next=p;
        q.rear=p;
    }
    
    //出队列
    void DeleteQueue(LinkQueue &q)
    {    
        if(q.rear==q.front){
            cout<<"队列为空"<<endl;
            return;
        }
        QNodePtr p;
        p=q.front->next;
        cout<<"出队列元素:"<<p->data<<endl;
        q.front->next=p->next;
        if(q.rear==p)        //防止删除最后一个元素时队列尾指针丢失
        {
            q.rear=q.front; //将队列的尾指针重新指向头指针
        }
        free(p);
    }
    //销毁队列
    void DestroyQueue(LinkQueue &q)
    {    
        while(q.front)
        {
            q.rear=q.front->next; //用尾指针记录当前指针移动的位置,减少再定义一个变量
            free(q.front);
            q.front=q.rear;
        }
    }
    //打印队列
    void print(LinkQueue &q)
    {    
        if(q.rear==q.front){
            cout<<"队列为空"<<endl;
            return;
        }
        QNodePtr p=q.front;
        cout<<"队列列表:";
        while(p!=q.rear)
        {
            p=p->next;
            cout<<p->data<<"    ";
        }
        cout<<endl;
    }
    int main(int argc,char* argv[])
    {
        LinkQueue q;
        int e;
        InitQueue(q);
        InsertQueue(q,1);
        InsertQueue(q,2);
        InsertQueue(q,3);
        InsertQueue(q,4);
        print(q);
        DeleteQueue(q);
        DeleteQueue(q);
        DestroyQueue(q);
        DeleteQueue(q);
        cin>>e;
        return 0;
    }
  • 相关阅读:
    JAVA编程心得-JAVA实现CRC-CCITT(XMODEM)算法
    自学PHP 环境搭建
    Postfix+Amavisd-new+Spamassassin+ClamAV整合安装
    安装Apache Felix OSGI Framework小记
    C#多线程
    使用maven进行测试设置断点调试的方法
    2016第33周四
    Spring配置文件头及xsd文件版本
    2016第33周二
    web中的重定向与转发
  • 原文地址:https://www.cnblogs.com/lbangel/p/3328608.html
Copyright © 2020-2023  润新知