数据结构与算法C语言——队列的基本操作

数据结构与算法——队列

雨中漫步

任意输入队列长度和队列中的元素值,构造一个顺序循环队列,对其进行清空、插入新元素、返回队头元素以及删除队头元素操作。
代码实现:

#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef int ElemType;
typedef struct
{
	ElemType data[MaxSize];
	int front,rear;		//队首和队尾指针
} SqQueue;
void InitQueue(SqQueue *&q)
{	q=(SqQueue *)malloc (sizeof(SqQueue));
	q->front=q->rear=0;
}
void DestroyQueue(SqQueue *&q)
{
	free(q);
}
bool QueueEmpty(SqQueue *q)
{
	return(q->front==q->rear);
}
bool enQueue(SqQueue *&q,ElemType e)
{	if ((q->rear+1)%MaxSize==q->front)	//队满上溢出
		return false;
	q->rear=(q->rear+1)%MaxSize;
	q->data[q->rear]=e;
	return true;
}
bool deQueue(SqQueue *&q,ElemType &e)
{	if (q->front==q->rear)		//队空下溢出
		return false;
	q->front=(q->front+1)%MaxSize;
	e=q->data[q->front];
	return true;
}
bool GetQueue(SqQueue *q,ElemType &e)
{
    if(q->front==q->rear)
        return false;
    else
    {
        int x=q->front+1;
        e=q->data[x];
        return true;
    }                //取队头元素
}
int main()
{
    SqQueue *s;
    InitQueue(s);
    int L,e,a,n;
    printf("请输入队长和队的元素值\n");
    scanf("%d",&L);
    while(L--)
    {
        scanf("%d",&e);
        enQueue(s,e);
    }
    n=20;
    while(n--)
    {
        printf("清空请按1,销毁请按2,进队请按3,出队请按4,返回队头请按5,结束请按6\n");
        scanf("%d",&a);
        if(a==1)
        {
            InitQueue(s);
            printf("清空成功!\n");
        }
        if(a==2)
        {
            DestroyQueue(s);
            printf("销毁成功!\n");
        }
        if(a==3)
        {
            printf("请输入队元素\n");
            scanf("%d",&e);
            if(enQueue(s,e))
            printf("进队成功!\n");
        }
        if(a==4)
        {
            if(deQueue(s,e))
            printf("出队成功!\n");
        }
        if(a==5)
        {
            if(GetQueue(s,e))
                printf("队头元素为%d\n",e);
        }
        if(a==6)
        {
           break;
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值