队列基本操作代码集合,来自《数据结构-用C语言描述》(第二版) 高教社
队列是受限制的链表或顺序表(只能从队首取结点,先进先出FIFO),相关操作可以查看之前的博客。
/*链队列*/
typedef struct {
QueueElemType data;
struct Node *next;
} LinkQueueNode;
typedef struct {
LinkQueueNode *front;
LinkQueueNode *rear;
} LinkQueue;
/*初始化*/
int InitQueue(LinkQueue *Q) {
Q->front = (LinkQueueNode *)malloc(sizeof(LinkQueueNode));
if(Q->front != NULL) {
Q->rear = Q->front;
Q->front->next = NULL;
return(TRUE);
}
else {
return(FALSE);
}
}
/*链队入队*/
int EnterQueue(LinkQueue *Q, QueueElemType x) {
LinkQueueNode *NewNode;
NewNode = (LinkQueueNode *)malloc(sizeof(LinkQueueNode));
if(NewNode != NULL) {
NewNode->data = x;
NewNode->next = NULL;
Q->rear->next = NewNode;
Q->rear = NewNode;
}
else {
printf("OVERFLOW:\n");
return(FALSE);
}
}
/*链队出队*/
int DeleteQueue(LinkQueue *Q, QueueElemType *x) {
LinkQueueNode *p;
if(Q->front == Q->rear) {
return(FALSE);
}
p = Q->front->next;
Q->front->next = p->next;
if(Q->rear == p) {
Q->rear = Q->front;
}
*x = p->data;
free(p);
return(TRUE);
}
/*循环队列*/
#define MAXSIZE 50
typedef struct {
QueueElemType elem[MAXSIZE];
int front;
int rear;
} SeqQueue;
void InitQueue(SeqQueue *Q) {
Q->front = Q->rear = 0;
}
/*循环队列入队操作*/
int EnterQueue(SeqQueue *Q, QueueElemType x) {
if((Q->rear + 1) % MAXSIZE == Q->front) {
printf("OVERFLOW");
return FALSE;
}
*x = Q->elem[Q->front];
Q->front = (Q->front+1) % MAXSIZE;
}
/*循环队列出队操作*/
int DeleteQueue(SeqQueue *Q, QueueElemType *x) {
if(Q->front == Q->rear) {
return(FALSE);
}
*x = Q->elem[Q->front];
Q->front = (Q->front - 1) % MAXSIZE;
return(TRUE);
}
zhihu:Solo | weibo@从流域到海域