链式队列的基本操作。
在传递参数时,要分清何时一定要对变量取地址,何时可取可不取。
在初始化函数中,由于需要修改主函数中queue指针的指向,为其分配空间,所以传递参数时要对其取地址。同理,在销毁队列的函数中,也需要取地址。
头文件源代码如下:
#ifndef _LINKQUEUE_H
#define _LINKQUEUE_H
#define SUCCESS 10000
#define FAILURE 10001
#define TRUE 10002
#define FALSE 10003
struct node //表示结点信息
{
int data; //数据域
struct node *next; //指针域
};
typedef struct node Node;
struct queue
{
Node *front; //队头指针
Node *rear; //队尾指针
};
typedef struct queue Q;
int queueinit(Q **q);
int queueinsert(Q*queue, int e);
int DeleteQueue(Q *q);
int GetFirst(Q *q);
int QueueEmpty(Q *q);
int ClearQueue(Q *q);
int QueueDestory(Q **q);
#endif
#include "LinkQueue.h"
#include<stdio.h>
#include<stdlib.h>
int queueinit(Q **q) //初始化
{
(*q) = (Q *)malloc(sizeof(Q));//存放队列信息,队头和队尾指针
if((*q) == NULL)
{
return FAILURE;
}
Node *p=(Node *)malloc(sizeof(Node));//保存结点信息
if(p == NULL)
{
return FAILURE;
}
p->next = NULL;
(*q)->front = (*q)->rear = p;//队头和队尾指针都指向头结点
return SUCCESS;
}
int queueinsert(Q *queue, int e)//入队
{
if(NULL == queue)
{
return FAILURE;
}
Node *q= (Node *)malloc(sizeof(Node));//新建结点
if (NULL == q)
{
return FAILURE;
}
q->data = e; //数据域
q->next = NULL; //指针域
queue->rear->next = q;//头结点指针域指向新建的结点
queue->rear = q; //队尾指针指向新的结点
return SUCCESS;
}
int DeleteQueue(Q *q)//删除结点
{
if (q == NULL || q->rear == q->front)
{
return FAILURE;
}
int e;
Node *p = q->front->next;
e = p->data;
q->front->next = p->next;
if (!p->next) //只剩下最后一个结点时,再出队,需要修改rear尾指针,在这之前rear都不需要动
{//特殊考虑
q->rear = q->front;
}
free(p);
return e;
}
int GetFirst(Q *q)
{
if(NULL == q || q->front == q->rear)
{
return FAILURE;
}
return q->front->next->data;
}
int QueueEmpty(Q *q)
{
if (q == NULL)
{
return 1;
}
return (q->front == q->rear) ? TRUE : FALSE;
}
int ClearQueue(Q *q) //清空队列
{
if(NULL == q)
{
return FAILURE;
}
Node *p = q->front->next;
while(p)
{
q->front->next = p->next;
free(p);
p = q->front->next;
}
q->rear = q->front;
return SUCCESS;
}
int QueueDestory(Q **q)
{
if (q == NULL || (*q) == NULL)
{
return FAILURE;
}
free((*q)->front); //释放头结点
free(*q);
*q = NULL;
return SUCCESS;
}
队列为空时,front、rear指针指向头结点。不为空时,front指向头结点,rear指向队尾元素。