数据结构与算法基础–第05周15–3.5队列的表示和实现4–3.5.3队列的链式表示和实现
若用户无法估计所用队列的长度,则宜采用链队列
// 最大队列长度
#define MAXQSIZE 100
typedef struct Qnode{
QElemType data;
struct Qnode* next;
}QNode, *QuenePtr;
typedef struct{
QuenePtr front; // 队头指针
QuenePtr rear; // 队尾指针
}LinkQuene;
队列是先进先出,元素 x 先进,则必须元素 x 先出。
Status InitQueue(LinkQueue& Q){
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if(!Q.front)
exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
算法思想:从队头结点开始,依次释放所有结点
Status DestroyQueue(LinkQueue& Q){
while(Q.front){
p = Q.front->next;
free(Q.front);
Q.front = p;
}
return OK;
}
或者
Status DestroyQueue(LinkQueue& Q){
while(Q.front){
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
return OK;
}
Status EnQueue(LinkQueue& Q, QElemType e){
p = (QueuePtr)malloc(sizeof(QNode));
if(!p)
exit(OVERFLOW);
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
Status DeQueue(LinkQueue& Q, QElemType& e){
if(Q.front == Q.rear)
return ERROR;
p = (QueuePtr)malloc(sizeof(QNode));
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if(Q.rear == p)
Q.rear = Q.front;
delete p;
return OK;
}
Status GetHead(LinkQueue Q, QElemType& e){
if(Q.front == Q.rear)
return ERROR;
e = Q.front->next->data;
return OK;
}