参考:数据结构与算法分析 --C语言描述
使用链表来实现队列的时候,就不存在队满的情况了,入队就是在一端加入一个节点,出队就是在另一端删除一个节点。当然队首在链表的首或者尾都无所谓,但是最好在队首,那么入队就是使用的头插法建立链表。
特别注意,当队列中只有一个元素时出队,rear指针要修改为指向头节点。
代码
队首在链表首,建立头节点。
queue.h
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
typedef int ElementType;
struct QueueRecord;
struct Node;
typedef struct QueueRecord *Queue;
int IsEmpty(Queue Q);
Queue CreateQueue();
void DisposeQueue(Queue Q); //销毁队列
void MakeEmpty(Queue Q);
void Enqueue(Queue Q,ElementType X);
void Dequeue(Queue Q);
ElementType Front(Queue Q);
ElementType FrontAndDequeue(Queue Q); //返回队首元素并出队
#endif // QUEUE_H_INCLUDED
queue.c
#include"..\fatal.h"
#include"queue.h"
#include<stdio.h>
#include<stdlib.h>
struct QueueRecord{
struct Node *Head;
struct Node *Rear;
int Size;
};
struct Node{
ElementType Element;
struct Node *Next;
};
int IsEmpty(Queue Q){
return Q->Size == 0;
}
Queue CreateQueue(){
Queue Q = malloc(sizeof(struct QueueRecord));
if(Q == NULL)
FatalError("Out of Space!!");
Q->Head = malloc(sizeof(struct Node));
if(Q->Head == NULL)
FatalError("Out of Space!!");
Q->Head->Next = NULL;
Q->Rear = Q->Head;
Q->Size = 0;
return Q;
}
void MakeEmpty(Queue Q){
struct Node *p = Q->Head->Next;
struct Node *temp;
while(p != NULL){
temp = p;
p = p->Next;
free(temp);
}
Q->Head->Next = NULL;
Q->Rear = Q->Head;
Q->Size = 0;
}
void DisposeQueue(Queue Q){
if(Q == NULL)
return ;
MakeEmpty(Q);
free(Q->Head);
free(Q);
}
void Enqueue(Queue Q,ElementType X){
Q->Size ++;
struct Node *s = malloc(sizeof(struct Node));
s->Element = X;
s->Next = NULL;
Q->Rear->Next = s;
Q->Rear = s;
}
ElementType Front(Queue Q){
if(IsEmpty(Q))
Error("Empty Queue");
else
return Q->Head->Next->Element;
}
void Dequeue(Queue Q){
if(IsEmpty(Q))
Error("Empty Queue");
else{
struct Node *temp = Q->Head->Next;
if(Q->Rear == temp)
Q->Rear = Q->Head;
Q->Head->Next = temp->Next;
free(temp);
Q->Size --;
}
}
ElementType FrontAndDequeue(Queue Q){
ElementType X = 0;
if(IsEmpty(Q))
Error("Empty Queue");
else{
struct Node *temp = Q->Head->Next;
if(Q->Rear == temp)
Q->Rear = Q->Head;
X = temp->Element;
Q->Head->Next = temp->Next;
free(temp);
}
Q->Size --;
return X;
}
int main(){
Queue Q;
Q = CreateQueue(10);
Enqueue(Q, 1);
Enqueue(Q, 2);
Dequeue(Q);
printf("%d\n",Front(Q));
printf("%d\n",FrontAndDequeue(Q));
Enqueue(Q, 1);
printf("%d\n",Front(Q));
printf("%d",IsEmpty(Q));
DisposeQueue(Q);
return 0;
}