队列的特点就是先进先出(fifo),在队尾入队列,在队头出队列(现实生活中买火车票排队就和队列差不多,后面的人加入队列,前面买到票的人离开队列),下面代码实现了队列最基本的操作:
#include <stdio.h>
#include <stdlib.h>
#define Status int
#define OK 1
#define ERROR 0
typedef struct Qnode {
int data;
struct Qnode *next;
}Qnode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
Status InitQueue(LinkQueue *Q) {
Q->front = Q->rear = (QueuePtr)malloc(sizeof(Qnode));
if (! Q->front) {
exit(-1);
}
Q->front->next = NULL;
return OK;
}
Status EnQueue(LinkQueue *Q,int e) {
QueuePtr p;
p = (QueuePtr)malloc(sizeof(Qnode));
if (!p) {
exit(-1);
}
p->data = e;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
return OK;
}
Status DeQueue(LinkQueue *Q,int *e) {
QueuePtr p;
if (Q->front == Q->rear) {
return ERROR;
}
p = Q->front->next;
*e = p->data;
Q->front->next = p->next;
if(Q->rear == p) {
Q->rear = Q->front;
}
free(p);
return OK;
}
int main()
{
LinkQueue Q;
int e,x;
InitQueue(&Q);
printf("please input the elment,end with -1:");
scanf("%d",&x);
while (x != -1) {
EnQueue(&Q,x);
scanf("%d",&x);
}
while(Q.rear != Q.front) {
DeQueue(&Q,&e);
printf("%d ",e);
}
return 0;
}
上述代码复制过去就可以执行,原理比较简单。