#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int status;
typedef int ElemType;
#define MAXSIZE 100
typedef struct
{
ElemType base[MAXSIZE];
int front;
int rear;
}SqQueue;
//循环队列
status InitQueue(SqQueue *Q)
{
Q->front=0;
Q->rear=0;
return OK;
}
status EnQueue(SqQueue *Q,ElemType e)
{
if((Q->rear+1)%MAXSIZE==Q->front)
return ERROR;
Q->base[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXSIZE;
return OK;
}
status DeQueue(SqQueue *Q,ElemType *e)
{
if(Q->front==Q->rear)
return ERROR;
*e=Q->base[Q->front];
Q->front=(Q->front+1)%MAXSIZE;
return OK;
}
ElemType GetHead(SqQueue Q)
{
if(Q.front==Q.rear)
return ERROR;
return Q.base[Q.front];
}
bool QueueEmpty(SqQueue Q)
{
return Q.front==Q.rear;
}
//链队
typedef struct QNode
{
ElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
status InitQueueNode(LinkQueue *Q)
{
Q->front=Q->rear=(QNode *)malloc(sizeof(QNode));
Q->front->next=NULL;
return OK;
}
status EnQueueNode(LinkQueue *Q,ElemType e)
{
QNode *p=(QNode *)malloc(sizeof(QNode));
p->data=e;
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
return OK;
}
status DeQueueNode(LinkQueue *Q,ElemType *e)
{
if(Q->front==Q->rear)
return ERROR;
QNode *p=Q->front->next;
*e=p->data;
Q->front->next=p->next;
if(Q->rear==p)//最后一个元素被删,队尾指回队头
Q->rear=Q->front;
free(p);
return OK;
}
ElemType GetHeadNode(LinkQueue Q)
{
if(Q.front!=Q.rear)
return Q.front->next->data;
}
int main()
{
//循环队列
/*
SqQueue Q;
InitQueue(&Q);
int i,num=5;
for(i=0;i<num;i++)
{
EnQueue(&Q,i+1);
printf("enqueue: %d\n",i+1);
}
printf("head of the queue:%d\n",GetHead(Q));
ElemType a;
for(i=0;i<num;i++)
{
DeQueue(&Q,&a);
printf("dequeue: %d\n",a);
}
*/
//链队
LinkQueue Q;
InitQueueNode(&Q);
int i,num=5;
for(i=0;i<num;i++)
{
EnQueueNode(&Q,i+1);
printf("enqueue: %d\n",i+1);
}
printf("head of the queue:%d\n",GetHeadNode(Q));
ElemType a;
for(i=0;i<num;i++)
{
DeQueueNode(&Q,&a);
printf("dequeue: %d\n",a);
}
return 0;
}
数据结构C语言-循环队列、链队
最新推荐文章于 2022-05-22 09:32:48 发布