顺序表的实现:
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int front, rear;
}SQUEUE;
void initQueue(SQUEUE *sq)
{
sq->rear = sq->front = 0;
}
int EnQueue(SQUEUE *sq, ElemType x)
{
if((sq->rear + 1) % MaxSize == sq->front)
{
printf("\n queue is full");
return 0;
}
sq->rear = (sq->rear + 1) % MaxSize;
sq->data[sq->rear] = x;
return 1;
}
int Empty(SQUEUE *sq)
{
return (sq->rear == sq->front) ? 1 : 0;
}
int OutQueue(SQUEUE *sq, ElemType *x)
{
if(Empty(sq))
{
printf(" \n queue is free");
return 0;
}
sq->front = (sq->front + 1) % MaxSize;
*x = sq->data[sq->front];
return 1;
}
int getHead(SQUEUE *sq, ElemType *x)
{
if(Empty(sq))
{
printf("\n queue is free");
return 0;
}
*x = sq->data[(sq->front + 1) % MaxSize];
return 1;
}
int main()
{
ElemType x;
SQUEUE sq;
initQueue(&sq);
EnQueue(&sq, 10);
getHead(&sq, &x);
printf("%d\n", x);
EnQueue(&sq, 20);
getHead(&sq, &x);
printf("%d\n", x);
system("pause");
return 0;
}
链表的实现:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct qnode{
ElemType data;
struct qnode *next;
}QTYPE;
typedef struct qptr{
QTYPE *front, *rear;
}SQUEUE;
SQUEUE LQ;
void initQueue(SQUEUE *lq)
{
QTYPE *p;
p = (QTYPE*)malloc(sizeof(QTYPE));
p->next = NULL;
lq->front = lq->rear = p;
}
int EnQueue(SQUEUE *lq, ElemType x)
{
QTYPE *s;
s = (QTYPE*)malloc(sizeof(QTYPE));
s->data = x;
s->next = lq->rear->next;
lq->rear->next = s;
lq->rear = s;
return 1;
}
int Empty(SQUEUE *lq)
{
return (lq->front == lq->rear ? 1 : 0);
}
int OutQueue(SQUEUE *lq, ElemType *x)
{
QTYPE *p;
if(Empty(lq))
{
printf("\n queue is free");
return 0;
}
p = lq->front->next;
*x = p->data;
lq->front->next = p->next;
if(lq->front->next == NULL)
lq->rear = lq->front;
free(p);
return 1;
}
int getHead(SQUEUE *lq, ElemType *x)
{
if(Empty(lq))
{
printf("\n queue is free");
return 0;
}
*x = lq->front->next->data;
return 1;
}
int main()
{
ElemType x;
initQueue(&LQ);
EnQueue(&LQ, 10);
getHead(&LQ, &x);
printf("%d\n", x);
EnQueue(&LQ, 20);
getHead(&LQ, &x);
printf("%d\n", x);
OutQueue(&LQ, &x);
printf("%d\n", x);
system("pause");
return 0;
}