队列(顺序表)基本操作实现(c语言)

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef int ElemType;
typedef struct node{
    int front;
    int rear;
    ElemType data[MAX_SIZE];
}*queueList,queueNode;
//顺序队列初始化
queueList initQueueList()
{
      queueList q=(queueList)malloc(sizeof(queueNode));
      if(!q)
      {
            printf("动态内存分配失败!\n");
            exit(0);
      }
      q->front=0;
      q->rear=0;
      printf("队列初始化成功!\n");
      return q;
}
//入队列
int enQueue(queueList q,ElemType e)
{
      if((q->rear+1)%MAX_SIZE==q->rear)
      {
            printf("队列已满!");
            return 0;
      }
      q->data[q->rear]=e;
      q->rear=(q->rear+1)%MAX_SIZE;
      return 1;

}
//出队列
int deQueue(queueList q,ElemType *e)
{
      if(q->rear==q->front)
      {
            printf("\n队列为空");
            return 0;
      }
      *e=q->data[q->front];
      q->front=(q->front+1)%MAX_SIZE;
      return 1;
}
//判断队列是否为空
int isEmpty(queueList q)
{
      if(q->rear==q->front)
      {
            return 1;
      }
      return 0;
}
//获取队头元素
int getHead(queueList q)
{
    if(!isEmpty(q))
    {
          return q->data[q->front];

    }
    return 0;
}
//清空队列
int clearQueue(queueList q)
{
      if(q)
      {
             q->rear=q->front=0;
             return 1;

      }
      return 0;

}
//求队列长度
int queueLength(queueList q)
{
      return q->rear-q->front;
}


int main()
{
    queueList q=initQueueList();
    if(isEmpty(q))
    {
          printf("当前队列为空!\n");
    }
    int n,a[MAX_SIZE],i,d,head,length;
    printf("请输入数字n:\n");
    scanf("%d",&n);
    printf("请输入%d个数:\n",n);
    for(i=0;i<n;i++)
    {
          scanf("%d",&a[i]);
          enQueue(q,a[i]);
          head=getHead(q);
          length=queueLength(q);
          printf("当前队列长度为%d,队头元素为%d\n",length,head);

    }
    printf("打印出队序列:\n");

    while(deQueue(q,&d))
    {
          printf("%d ",d);
    }


    return 0;
}

猜你喜欢

转载自blog.csdn.net/rj2017211811/article/details/85059847