循环队列以及链队列的实现(C语言)

#define OK 1

#define ERROR 0

#define MAXSIZE 10

typedef int Status;

typedef int QElemType;

#if 0

/*循环链表的存储结构*/

typedef struct

{

QElemType data[MAXSIZE ];

int front;

int rear;

}SqQueue;

 

Queue.c

/*初始化循环队列*/

Status InitQueue(SqQueue *Q)

{

Q->front = 0;

Q->rear= 0;

 

return OK;

}

/*循环队列当前长度*/

Status LengthQueue(SqQueue  q)

{

return (q.rear-q.front+MAXSIZE )%MAXSIZE ;

}

/*插入元素e为新的队尾元素*/

Status EnQueue(SqQueue *Q, QElemType e)

{

if((Q->rear+1)%MAXSIZE  == Q->front)

{

return ERROR;

}

Q->data[Q->rear] = e;

Q->rear = (Q->rear+1)%MAXSIZE ;/*若到最后则转到数组头部*/

return OK;

}

/*若队列不为空,则删除队头元素*/

Status DeQueue(SqQueue *Q, QElemType *e)

{

if(Q->front == Q->rear)

{

return ERROR;

}

*e = Q->data[Q->front];

Q->front = (Q->front+1)%MAXSIZE ;

 

return OK;

}

/*打印循环队列中的元素*/

void PrintQueue(SqQueue  q)

{

int i = q->front;

while(i%MAXSIZE  != q.rear)

{

printf("%d ", q.data[i%MAXSIZE]);

i++;

}

printf("\n");

}

#endif

 

#if 1

/*链队列的存储结构*/

typedef struct QNode

{

QElemType data;

struct QNode *next;

}QNode, *QueuePtr;

typedef struct

{

QueuePtr front, rear;

}LinkQueue;

/*链队列的初始化*/

Status InitLinkQueue(LinkQueue *Q)

{

QueuePtr Pn = (QueuePtr )malloc(sizeof(QNode));

if(!Pn)

{

return ERROR;

}

Pn ->next = NULL;

Q->front = Pn;

Q->rear = Pn;

return OK;

}

/*链队列的队尾插入结点*/

Status EnLinkQueue(LinkQueue *Q, QElemType e)

{

QueuePtr Pn = (QueuePtr )malloc(sizeof(QNode));

if(!Pn)

{

return ERROR;

}

Pn ->data = e;

Pn ->next = NULL;

Q->rear->next = Pn ;

Q->rear = Pn ;

return OK;

}

/*删除链队列队头元素*/

Status DeLinkQueue(LinkQueue *Q, QElemType *e)

{

QueuePtr pn = NULL;

if(Q->front == Q->rear)

{

return ERROR;

}

pn  = Q->front->next;

*e = pn->data;

Q->front->next = pn->next;

if(pn == Q->rear)

{

Q->rear = Q->front;

}

free(pn);

return OK;

}

/*打印链队列中的元素*/

void PrintLinkQueue(LinkQueue  q)

{

QueuePtr pn = q.front->next;

while(pn != q.rear)

{

printf("%d ", pn->data);

pn = pn->next;

}

printf("%d\n", pn->data);

}

#endif

 

你可能感兴趣的:(队列,数据结构,C语言)