定义
#define QueueSize 6
typedef struct node{
int data;
struct node *next;
}QueueNode;
typedef struct {//封装头尾指针
QueueNode *front;
QueueNode *real;
}Queue;
实现
#include"stdio.h"
#include"stdlib.h"
#include"s.h"
void InitQueue(Queue *p){//初始化
p->front =NULL;
p->real =NULL;
}
int EmptyQueue(Queue *P){//探空
if(P->front ==NULL&&P->real ==NULL)
return 1;
else
return 0;
}
void EnterQueue(Queue *p,int x){//入队
QueueNode *q=(QueueNode*)malloc(sizeof(QueueNode));//每次入队分配一个节点
q->data =x;
q->next =NULL;
if(EmptyQueue(p)){//空队列则使两个指针都指向初始节点
p->real =q;
p->front =q;
}
else{
p->real ->next =q;
p->real =q;
}
}
int LeaveQueue(Queue *p){//离队
int x;
QueueNode *q;
q=p->front ;
x=q->data ;
p->front =q->next ;
if(p->real ==q){//若只有一个节点,则使队尾指针为空
p->real =NULL;
}
free(q);
return x;
}
main(){
Queue *p;
int i,x;
int arr[]={1,2,3,4,5,6};
p=(Queue*)malloc(sizeof(Queue));
InitQueue(p);
for(i=0;i<QueueSize;i++){
EnterQueue(p,arr[i]);
}
for(i=0;i<QueueSize;i++){
x=LeaveQueue(p);
printf("%d ",x);
}
system("pause");
}