3.5.3队列的链式存储及实现
1、链队列的初始化
// 1、链队列的初始化
Status InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
Q.front->next = NULL;
return OK;
}
2、销毁链队列
// 2、销毁链队列
Status DestoryQueue(LinkQueue &Q){
QNode *p;
while(Q.front){
p = Q.front->next;
free(Q.front);
Q.front = p;
}
return OK;
}
3、求链队列的长度
// 3、求链队列的长度
int LengthQueue(LinkQueue &Q){
int num = 0;
QNode *p;
if(Q.front == Q.rear){
return 0;
}
p = Q.front->next;
while(p){
p = p->next;
num++;
}
return num;
}
4、链队列入队
// 4、链队列入队
Status EnQueue(LinkQueue &Q,QElemType e){
QNode *p;
p = (QueuePtr)malloc(sizeof(QNode));
if(!p){
return ERROR;
}
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
5、链队列出队
// 5、链队列出队
Status DeQueue(LinkQueue &Q,QElemType e){
QNode *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;
}
delete p;
return OK;
}
6、求链队列的对头元素
// 6、求链队列的对头元素
QElemType GetHead(LinkQueue Q,QElemType e){
if(Q.front = Q.rear){
return ERROR;
}
e = Q.front->next->data;
return e;
}
代码测试
# include<Stdio.h>
#include <stdlib.h>
# define OK 1
# define ERROR 0
# define MAXQSIZE 100
typedef int QElemType;
typedef int Status;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
// 1、链队列的初始化
Status InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
Q.front->next = NULL;
return OK;
}
// 2、销毁链队列
Status DestoryQueue(LinkQueue &Q){
QNode *p;
while(Q.front){
p = Q.front->next;
free(Q.front);
Q.front = p;
}
return OK;
}
// 3、求链队列的长度
int LengthQueue(LinkQueue &Q){
int num = 0;
QNode *p;
if(Q.front == Q.rear){
return 0;
}
p = Q.front->next;
while(p){
p = p->next;
num++;
}
return num;
}
// 4、链队列入队
Status EnQueue(LinkQueue &Q,QElemType e){
QNode *p;
p = (QueuePtr)malloc(sizeof(QNode));
if(!p){
return ERROR;
}
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
// 5、链队列出队
Status DeQueue(LinkQueue &Q,QElemType e){
QNode *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;
}
delete p;
return OK;
}
// 6、求链队列的对头元素
QElemType GetHead(LinkQueue Q,QElemType e){
if(Q.front = Q.rear){
return ERROR;
}
e = Q.front->next->data;
return e;
}
int main(){
}