数据结构之队列

 

#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;
}

 

转载于:https://www.cnblogs.com/lbangel/p/3328608.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值