链队列基本操作实现(c语言)

#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct
{
    ElemType data;
    struct node*next;
} linkQNode;
typedef struct qnode
{
    linkQNode* rear;
    linkQNode* front;
}*linkQueue;

//链队列初始化
linkQueue initLinkQueue()
{
    linkQueue q=(linkQueue)malloc(sizeof(struct qnode));
    q->front=(linkQNode*)malloc(sizeof(linkQNode));

    q->rear=q->front;
    q->front->next=NULL;
    printf("链队列初始化成功!\n");
    return q;

}
//入队列
int enQueue(linkQueue q,ElemType e)
{
    linkQNode *p=(linkQNode*)malloc(sizeof(linkQNode));
    if(p)
    {
        p->data=e;
        p->next=NULL;
        q->rear->next=p;
        q->rear=p;
        return 1;
    }
    return 0;
}
//出队列
int deQueue(linkQueue q,ElemType *e)
{
    linkQNode* p;
    if(q->rear!=q->front)
    {

        p=q->front->next;
        q->front->next=p->next;

        if(q->rear==p)//如果队列只有一个元素,变成空队列
        {
              q->rear=q->front;
        }
        *e=p->data;
        return 1;
    }
    return 0;

}
//获取队头元素
int getQueueHead(linkQueue q)
{

      if(q->rear!=q->front)
      {
             linkQNode *p=q->front->next;
            return p->data;
      }
      return 0;
}
//判断队空
int isEmpty(linkQueue q)
{
      if(q->rear==q->front)
      {
            return 1;
      }
      return 0;
}
//销毁队列
void destoryQueue(linkQueue q)
{
      linkQNode *p;

      while(!isEmpty(q))
      {
            p=(linkQNode*)malloc(sizeof(linkQNode));
            p=q->front->next;
            free(p);

      }
      printf("队列已经销毁!\n");

}
int main()
{
    linkQueue q=initLinkQueue();
    if(isEmpty(q))
    {
          printf("当前队列为空!\n");
    }
    int n,i,a[100],d,head;
    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=getQueueHead(q);
        printf("当前队列队头元素为%d\n",head);

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

    while(deQueue(q,&d))
    {
        printf("%d ",d);
    }
    if(isEmpty(q))
    {
          printf("\n当前队列为空!\n");
    }
    destoryQueue(q);




    return 0;
}

猜你喜欢

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