//链队列
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define OVERFLOW 0
#define OK 1
#define ERROR 0
typedef int Elemt;
//链队列结点
typedef struct QNode{
int data;
struct QNode * next;
}QNode,*QueuePtr;
//链对列的头结点和为结点
typedef struct {
QueuePtr front ;
QueuePtr rear;
}LinkQueue;
// 构建一个空的链队列
Elemt creat_Queue(LinkQueue &Q){
Q.rear=Q.front=(QueuePtr)malloc(sizeof(QNode)) ;
if(!Q.rear) exit(OVERFLOW);
Q.front->next=NULL;
printf("creat successful!!!\n");
return OK;
}
//销毁该链队列
Elemt destory_Queue(LinkQueue &Q){
while(Q.front){
Q.rear=Q.front->next;
free(Q.front);
Q.front=Q.rear;
}
printf("destory successful!!!\n");
return OK;
}
//判断链对列是否为空,若为空返回OK,否则返回ERROR
Elemt determin_Queue_null(LinkQueue &Q){
if(Q.front==NULL) return OK;
else return ERROR;
}
//将该链队列清空
void clear_Queue(LinkQueue &Q){
destory_Queue(Q);
creat_Queue(Q);
}
//判断该链队列的长度,用 e返回
void Queue_lengtu(LinkQueue Q,int &e){
int n=0;
QueuePtr p=Q.front;
while(p!= Q.rear){
n++;
p=p->next ;
}
e=n;
}
//用e返回该链队列的队头
Elemt Gethead(LinkQueue Q,int &e ){
QueuePtr p;
p=Q.front;
if(Q.front == Q.rear) return ERROR;
p=p->next;
e=p->data;
return OK;
}
Elemt in_Queue(LinkQueue &Q,int e){
QueuePtr p;
p=(QueuePtr)malloc(sizeof(QNode));
if(!p) return ERROR;
p->data = e;
p->next =NULL;
Q.rear->next=p;//这是将该结点连接到为部
Q.rear=p; //这是将该尾部指针指向p(注意这里没有使用Q.rear->next,使用了Q.rear,表示这个结点,指向,而不改变原来的位置的值)
return OK;
}
//若队列不为空,则删除队头元素
Elemt DEL_Queue_F(LinkQueue &Q){
QueuePtr p;
p=Q.front->next;
if(determin_Queue_null(Q)) return ERROR;
Q.front->next=p->next;
if(Q.rear == p) {Q.rear = Q.front; return ERROR;}//注意这里若删除的第一个结点恰好是尾结点的话,是将Q.rear指向Q.front,不能 Q.front=Q.rear(因为此时要删除该尾结点,而不是删除真个链表)
free(p);
return OK;
}
//遍历该链队列
Elemt bian_li_Queue(LinkQueue Q){
QueuePtr p;
if(determin_Queue_null(Q)) return ERROR;
p=Q.front->next;
while(p != NULL){
printf("%d\n",p->data);
p=p->next;
}
return OK;
}
int main(){
LinkQueue Q;
int e,n;
creat_Queue(Q);
//clear_Queue(Q);
//Queue_lengtu(Q,e);
for(n=0;n<3;n++){
printf("input your e:\n");
scanf("%d",&e);
in_Queue(Q,e);
}
bian_li_Queue(Q);
//删除链队列头元素
//DEL_Queue_F(Q);
//用e返回该链队列的头元素
//Gethead(Q,e);
//printf("e is : %d\n" , e);
destory_Queue(Q);
return OK;
}