链式队列模板

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int status;
typedef int elemtype;
typedef struct qnode{
    elemtype data;
    struct qnode *next;
}qnode,*ptr;
typedef struct {
    ptr head;
    ptr tail;
}linkqueue;
status initqueue(linkqueue &q){//初始化队列

      q.head=q.tail=(ptr)malloc(sizeof(qnode));
     if(!q.head)
        exit(OVERFLOW);
        q.head->next=NULL;
        return OK;
}
status enqueue(linkqueue &q,elemtype e){//向队列插入元素
     ptr p=(ptr)malloc(sizeof(qnode));
     if(!p)
         exit(OVERFLOW);
     p->next=NULL,p->data=e;
     q.tail->next=p;
     q.tail=p;
     return OK;
}

status dequeue(linkqueue &q,elemtype &e){//删除队首元素
    if(q.head==q.tail)
        return ERROR;
    ptr p=(ptr)malloc(sizeof(qnode));
    p=q.head->next;
    e=p->data;
    q.head->next=p->next;
    if(q.tail==p)
        q.tail=q.head;
    free(p);
    return OK;
}

status destroy(linkqueue &q){//销毁队列链表
     while(q.head){
        q.tail=q.head->next;
        free(q.head);
        q.head=q.tail;
     }
     return OK;
}
int get_len(linkqueue q){//获得队列长度
  int cnt=0;
  while(q.head->next!=NULL){
       q.tail=q.head->next;
       cnt++;
       q.head=q.tail;
    }
    return cnt;
}
status print(linkqueue q){//输出线性表元素
    while(q.head->next!=NULL){
       q.tail=q.head->next;
       printf("%d  ",q.tail->data);
       q.head=q.tail;
    }
    printf("
");
    return OK;
}
status gethead(linkqueue q,elemtype &e){//获得队首元素
    ptr p=(ptr)malloc(sizeof(qnode));
    p=q.head->next;
    e=p->data;
    return OK;
}
status qempty(linkqueue q){//判断是否为空
    if(q.head==q.tail)
        return TRUE;
    else
        return FALSE;
}
status clearqueue(linkqueue &q){ // 将q清为空队列
  ptr p1,p2;
  q.tail=q.head;
  p1=q.head->next;
  q.head->next=NULL;
  while(p1)
  {
    p2=p1;
    p1=p1->next;
    free(p2);
  }
  return OK;
}
int main(){
    linkqueue q;
    initqueue(q);
    elemtype e;
    for(int i=1;i<=5;i++){
        enqueue(q,i);
    }
    gethead(q,e);
    printf("%d
",e);//输出队首元素


    print(q);
    printf("%d
",get_len(q));
    dequeue(q,e);
     enqueue(q,10);
     print(q);
     printf("%d
",get_len(q));
        int flag=qempty(q);//判断是否为空时候使用
    printf("%d
",flag);
     clearqueue(q);//清空队列时候使用
    return 0;
}
原文地址:https://www.cnblogs.com/13224ACMer/p/5037752.html