队列的顺序存储

队列的顺序存储

队列的顺序存储

队列的顺序存储

“a.h”


 #include
 #include
 #include
 #include
 #include
 #include
 #include
 #include
 #include
 
 #define TRUE 1
 #define FALSE 0
 #define OK 1
 #define ERROR 0

typedef int Status;
typedef int ElemType;

#define MAXSIZE 10
typedef struct {
     ElemType *base;
  int front;     //不是指针,是整数用来指示顺序表的元素。
  int rear;
 }Queue;

 

"b.h"

#include"b.c"
Status InitQueue(Queue *q);

Status DestroyQueue(Queue *q);

Status ClearQueue(Queue *q);

Status QueueEmpty(Queue q);

Status QueueLength(Queue q);

Status GetHead(Queue q,ElemType *e);

Status InsertQueue(Queue *q,ElemType e);

Status DeleteQueue(Queue *q,ElemType *e);

Status QueueTraverse(Queue q,Status(*fun)(ElemType));

 

"b.c"

#include"a.h"
Status InitQueue(Queue *q)
{
    (*q).base=(ElemType*)malloc(MAXSIZE*sizeof(ElemType));
 if(!(*q).base)
  return ERROR;
 (*q).front=(*q).rear=0;
 return OK;
}

Status DestroyQueue(Queue *q)
{
    if((*q).base)
  free((*q).base);
 (*q).base=0;
 (*q).front=(*q).rear=0;
 return OK;
}

Status ClearQueue(Queue *q)
{
     (*q).front=(*q).rear=0;
  return OK;
}

Status QueueEmpty(Queue q)
{
     if(q.front==q.rear)
   return TRUE;
  else
   return FALSE;
}

Status QueueLength(Queue q)
{
      return (q.rear-q.front+MAXSIZE)%MAXSIZE;
  
}

Status GetHead(Queue q,ElemType *e)
{
      if(q.front==q.rear)
    return ERROR;
   else
    *e=*(q.base+q.front);
 return OK;
}

Status InsertQueue(Queue *q,ElemType e)
{
       if(((*q).rear+1)%MAXSIZE==(*q).front)
     return ERROR;
    *((*q).base+(*q).rear)=e;            //队列头指针在尾指针的下一位置即为满,牺牲一个存储空间
    (*q).rear=((*q).rear+1)%MAXSIZE;
    return OK;
}
Status DeleteQueue(Queue *q,ElemType *e)
{
      if((*q).front==(*q).rear)
    return ERROR;
   *e=(*q).base[(*q).front];
   (*q).front=((*q).front+1)%MAXSIZE;    //一切的%MAXSIZE 都是为了循环
   return OK;
}

Status QueueTraverse(Queue q,Status(*fun)(ElemType))
{
       int i=q.front;
    printf("队头  ");
       while(i!=q.rear){
         fun(q.base[i]);
   i=(i+1)%MAXSIZE;
    }
    printf("队尾\n");
    return OK;
}

"main.c"

#include"b.h"

Status fun(ElemType e)
{
    printf(" %d ",e);
 return OK;
}

int main()
{
 ElemType e;
 int i;
    Queue q;
 InitQueue(&q);
 for(i=0;i<9;i++){
  printf("请输入插入元素的值:");
  scanf("%d",&e);
        InsertQueue(&q,e);
 }
 QueueTraverse(q,fun);
 for(i=0;i<7;i++){
     DeleteQueue(&q,&e);
  printf("删除的元素为 :%d\n",e);
 }
    QueueTraverse(q,fun);
 printf("队列的长度为 %d\n",QueueLength(q));

 for(i=0;i<7;i++){
  printf("请输入插入元素的值:");
  scanf("%d",&e);
        InsertQueue(&q,e);
 }
 QueueTraverse(q,fun);
 printf("队列的长度为 %d\n",QueueLength(q));
 if(!QueueEmpty(q))
  printf("队列不为空\n");

 return OK;
}

下面开始写一两个栈,队列的小的应用算法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值