您的位置:首页 > 理论基础 > 数据结构算法

第七周项目3-负数把正数赶出队列

2016-10-14 10:50 274 查看
<pre name="code" class="html">问题描述及代码:
[cpp] view plain copy
1.	/*
2.	*烟台大学计控学院
3.	*作    者:朱建豪
4.	*完成日期:2016年10月14日
5.	*问题描述:设从键盘输入一整数序列a1,a2,…an,试编程实现:当ai>0时,ai进队,当ai<0时,将队首元素出队,当ai=0时,表示输入结束。要求将队列处理成环形队列,使用算法库中定义的数据类型及算法,程序中只包括一个函数(main函数),入队和出队等操作直接写在main函数中即可。当进队出队异常(如队满)时,要打印出错信息。
6.
7.	*/

(1)sqqueue.h
[cpp] view plain copy
1.	#ifndef SQQUEUE_H_INCLUDED
2.	#define SQQUEUE_H_INCLUDED
3.	#define MaxSize 5
4.	typedef int ElemType;
5.	typedef struct
6.	{
7.	    ElemType data[MaxSize];
8.	    int front,rear;     /*队首和队尾指针*/
9.	} SqQueue;
10.
11.
12.	void InitQueue(SqQueue *&q);  //初始化顺序环形队列
13.	void DestroyQueue(SqQueue *&q); //销毁顺序环形队列
14.	bool QueueEmpty(SqQueue *q);  //判断顺序环形队列是否为空
15.	int QueueLength(SqQueue *q);   //返回队列中元素个数,也称队列长度
16.	bool enQueue(SqQueue *&q,ElemType e);   //进队
17.	bool deQueue(SqQueue *&q,ElemType &e);  //出队
18.
19.
20.
21.
22.
23.	#endif // SQQUEUE_H_INCLUDED

(2)sqqueueu.cpp
[cpp] view plain copy
1.	#include"sqqueue.h"
2.	#include<stdio.h>
3.	#include<malloc.h>
4.	void InitQueue(SqQueue *&q)  //初始化顺序环形队列
5.	{
6.	    q=(SqQueue *)malloc (sizeof(SqQueue));
7.	    q->front=q->rear=0;
8.	}
9.	void DestroyQueue(SqQueue *&q) //销毁顺序环形队列
10.	{
11.	    free(q);
12.	}
13.	bool QueueEmpty(SqQueue *q)  //判断顺序环形队列是否为空
14.	{
15.	    return(q->front==q->rear);
16.	}
17.
18.
19.	int QueueLength(SqQueue *q)   //返回队列中元素个数,也称队列长度
20.	{
21.	    return (q->rear-q->front+MaxSize)%MaxSize;
22.	}
23.
24.	bool enQueue(SqQueue *&q,ElemType e)   //进队
25.	{
26.	    if ((q->rear+1)%MaxSize==q->front)  //队满上溢出
27.	        return false;
28.	    q->rear=(q->rear+1)%MaxSize;
29.	    q->data[q->rear]=e;
30.	    return true;
31.	}
32.	bool deQueue(SqQueue *&q,ElemType &e)  //出队
33.	{
34.	    if (q->front==q->rear)      //队空下溢出
35.	        return false;
36.	    q->front=(q->front+1)%MaxSize;
37.	    e=q->data[q->front];
38.	    return true;
39.	}

(3)main.cpp
[cpp] view plain copy
1.	#include <stdio.h>
2.	#include <malloc.h>
3.	#include "sqqueue.h"
4.	int main()
5.	{
6.	    ElemType a,x;
7.	    SqQueue *qu;    //定义队列
8.	    InitQueue(qu);  //队列初始化
9.	    while (1)
10.	    {
11.	        printf("输入a值(输入正数进队,负数出队,0结束):");
12.	        scanf("%d", &a);
13.	        if (a>0)
14.	        {
15.	            if (!enQueue(qu,a))
16.	                printf("  队列满,不能入队\n");
17.	        }
18.	        else if (a<0)
19.	        {
20.	            if (!deQueue(qu, x))
21.	                printf("  队列空,不能出队\n");
22.	        }
23.	        else
24.	            break;
25.	    }
26.	    return 0;
27.	}

运行结果:
<img src="http://img.blog.csdn.net/20161014105059033?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
知识点总结:
环形队列的基本运算及while循环语句
学习心得:
这才读懂题目意思,只是在键盘输入的时候让负数出队,理解了意思算法也就明白了



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  csdn 数据结构