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

来源:互联网 发布:知乎 日本人的遥远旅途 编辑:程序博客网 时间:2024/06/13 22:31
/*  
 * Copyright (c) 2016, 烟台大学计算机与控制工程学院  
 * All rights reserved。  
 * 文件名称 :1.cpp  
 * 作    者 :孟令群  
 * 完成日期 :2016年 10月8日  
 * 版 本 号 :v1.0  
 *  
 * 问题描述 :设从键盘输入一整数序列a1,a2,...an,试编程实现:当ai>0时,ai进队,当ai<0时,将队首元素出队,当ai=0时,表示输入结束。要求将队列处理成环形队列,使用环形队列算法库中定义的数据类型及算法,程序中只包括一个函数(main函数),入队和出队等操作直接在main函数中调用即可。当进队出队异常(如队满)时,要打印出错信息
 
 * 输入描述 : 
 * 输出描述 : 

 */   

//1、头文件sqqueue.h中定义数据结构并声明用于完成基本运算的函数。#ifndef SQQUEUE_H_INCLUDED      #define SQQUEUE_H_INCLUDED      #define MaxSize 5      typedef char ElemType;      typedef struct      {          ElemType data[MaxSize];          int front,rear;     /*队首和队尾指针*/      } SqQueue;       void InitQueue(SqQueue *&q);  //初始化顺序环形队列      void DestroyQueue(SqQueue *&q); //销毁顺序环形队列      bool QueueEmpty(SqQueue *q);  //判断顺序环形队列是否为空      int QueueLength(SqQueue *q);   //返回队列中元素个数,也称队列长度      bool enQueue(SqQueue *&q,ElemType e);   //进队      bool deQueue(SqQueue *&q,ElemType &e);  //出队      #endif // SQQUEUE_H_INCLUDED 
//2、在sqqueue.cpp中实现这些函数#include "sqqueue.h"  #include <malloc.h>  #include <stdio.h>  void InitQueue(SqQueue *&q) //初始化顺序环形队列      {  q=(SqQueue *)malloc(sizeof(SqQueue));  q->front=q->rear=-1;  }    void DestroyQueue(SqQueue *&q) //销毁顺序环形队列    {  free(q);  }    bool QueueEmpty(SqQueue *q) //判断顺序环形队列是否为空   {  return (q->front==q->rear);  }  int QueueLength(SqQueue *q)  //返回队列中元素个数,也称队列长度      {  return(q->rear-q->front+MaxSize)%MaxSize;  }  bool enQueue(SqQueue *&q,ElemType e) //进队      {  if(q->rear==MaxSize-1)  return false;  q->rear++;  q->data[q->rear]=e;  return true;  }    bool deQueue(SqQueue *&q,ElemType &e)//出队     {  if(q->front==q->rear)  return false;  q->front++;  e=q->data[q->front];  return true;  }   
//3、在main函数中完成测试#include"sqqueue.h"   #include <malloc.h>     #include<stdio.h>      int main()      {          ElemType a,x;          SqQueue *qu;          InitQueue(qu);          while(1)      {        printf("输入队列的值:");        scanf("%d",&a);         if(a>0)         {         if(!enQueue(qu,a))         printf("队列满。");          }         else if(a<0)         {         if(!deQueue(qu,x))             printf("队列为空。");         }         else              break;        }      return 0;      }      
运行结果:



学习心得:

有不会的问题是要向同学请教。

0 0