链队的操作实现

/*
@李德坤  烟台大学计算机与控制工程学院
我自己对链队的理解,链队的front只要不是出队操作始终指向第一个进入的元素,而rear随着元素入队由指向第一个进入的元素逐渐后移(指向下一个元素),当然front随着元素出队而逐渐后移(和rear移动方向一样)

例如
1 
2   1
3   2    1
4   3    2    1
5   4    3    2    1
rear和front移动的方向都是从1到5移动
*/

#include<stdio.h>
#include<stdlib.h>
typedef int Elemtype;
typedef struct qnode//链队数据节点类型定义
{
    Elemtype data;
    struct qnode *next;
} QNode;
typedef struct//相当于;链表中的头结点
{
    QNode *front;
    QNode *rear;
} LiQueue;
//初始化
void InitQueue(LiQueue * &q)
{
    q=(LiQueue*)malloc(sizeof(LiQueue));
    q->front=q->rear=NULL;
}
//销毁
void DestroyQueue(LiQueue *&q)
{
    QNode *p=q->front,*r;
    while(p!=NULL)
    {
        r=p->next;
        while(r!=NULL)
        {
            free(p);
            p=r;
            r=p->next;
        }
    }
    free(p);
    free(q);
}
//判断队列是否为空
bool QueueEmpty(LiQueue* &q)
{
    return (q->rear==NULL);
}
//入队
void enQueue(LiQueue *&q,Elemtype &e)
{
    QNode *p;
    p=(QNode*)malloc(sizeof(QNode));
    p->data=e;
    p->next=NULL;
    if(q->rear==NULL)
    {
        q->front=q->rear=p;
    }
    else
    {
        q->rear->next=p;
        q->rear=p;
    }
}
//单个出队,出一次队就删掉一个
void deQueue(LiQueue* &q,Elemtype &e)
{
    QNode *t;
    if(q->rear==NULL)
        printf("空队列!\n");
    else
    {
        if(q->front==q->rear)
            q->front=q->rear=NULL;
        e=q->front->data;
        t=q->front;
        q->front=q->front->next;
        free(t);
    }
}
//输出队列所有元素
void printtQueue(LiQueue *&q)
{
    QNode *p=q->front;
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}
int main()
{
    int i;
    LiQueue *q;
    InitQueue(q);
    for(i=0; i<5; i++)
    {
        enQueue(q,i);
        printf("入队成功!\n");
    }
    deQueue(q,i);
    printf("%d\n",i);
    deQueue(q,i);
    printf("%d\n",i);
    //DestroyQueue(q);销毁队列
    printtQueue(q);
    return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值