分类: C/C++
2011-05-24 11:07:36
/*
* 顺序队列
* Lzy 2011-5-23
*/
#include
#define Maxsize 100
#define ElemType int
typedef struct
{
ElemType data[Maxsize];
int front, rear;
}Squeue;
void QueueInit(Squeue *SQ)
{
SQ->front = SQ->rear = 0;
}
int QueuePush(Squeue *SQ, ElemType X)
{
if((SQ->rear +1) % Maxsize == SQ->front)
{
printf("Queue is full!\n");
return 0;
}
SQ->rear = (SQ->rear + 1) % Maxsize;
SQ->data[SQ->rear] = X;
return 1;
}
int IsEmpty(Squeue *SQ)
{
return SQ->rear == SQ->front ? 0:1;
}
int QueuePop(Squeue *SQ, ElemType *X)
{
if(IsEmpty == 0)
{
printf("Queue is free!\n");
return 0;
}
SQ->front = (SQ->front + 1) % Maxsize;
*X = SQ->data[SQ->front];
return 1;
}
/***测试程序***/
int main(void)
{
int i, d;
Squeue sq;
QueueInit(&sq);
for(i = 0; i < 16; i++)
QueuePush(&sq,i);
while(sq.front != sq.rear)
{
QueuePop(&sq,&d);
printf("%d ",d);
}
printf("\n");
}
/*
* 队列链试存储
* Lzy 2011-5-23
*/
#include
#define ElemType int
typedef struct node
{
ElemType data;
struct node *next;
}qnode;
typedef struct qptr
{
qnode *front, *rear;
}LSqueue;
void ListQueueInit(LSqueue **qp)
{
qnode *p = (qnode *)malloc(sizeof(qnode));
p->next = NULL;
(*qp) = (LSqueue *)malloc(sizeof(LSqueue));
(*qp)->rear = (*qp)->front = p;
}
int ListQueuePush(LSqueue *qp, ElemType X)
{
qnode *p = (qnode *)malloc(sizeof(qnode));
p->data = X;
p->next = qp->rear->next;
qp->rear->next = p;
qp->rear = p;
return 1;
}
int IsEmpty(LSqueue *qp)
{
return qp->front == qp->rear ? 0:1;
}
int ListQueuePop(LSqueue *qp, ElemType *X)
{
qnode *p;
if(IsEmpty == 0)
{
printf("Queue is free!\n");
return 0;
}
p = qp->front->next;
*X = p->data;
qp->front->next = p->next;
if(qp->front->next == NULL)
qp->front = qp->rear;
free(p);
return 1;
}
/*****测试程序*****/
int main(void)
{
int i,d;
LSqueue *LQ;
ListQueueInit(&LQ);
for(i = 0; i < 16; i++)
ListQueuePush(LQ,i);
while(LQ->front != LQ->rear)
{
ListQueuePop(LQ,&d);
printf("%d ",d);
}
printf("\n");
return 0;
}