队列的链式存储与相关操作

一、队列的链式存储与相关操作

注意

  1. 存储结构(带头结点)
    队列的链式存储与相关操作
    如图:q.frontq.front指向的单元为头结点,而队头的实际位置为q.front>nextq.front->next.
  2. q.popq.pop操作时,在释放队头指针前,应该先判断所poppop的元素是否是最后一个,是最后一个的话需要先将尾指针指向头指针,不然会造成尾指针的丢失。

代码

#include<iostream>
#include<cstring>
#include<cstdlib>
#define OK 1
#define ERROR -1
using namespace std;
typedef int ElemType;
typedef int Status;
typedef struct node{
	ElemType data;
	struct node *next;
}Qnode;
typedef struct {
	Qnode *front;  // 队头指针
	Qnode *rear;  // 队尾指针
}LinkQueue;
Status InitQueue(LinkQueue *q)
{
	q->front = q->rear = (Qnode *)malloc(sizeof(Qnode));
	if (!q->front)
		return ERROR;
	return OK;
}
bool QueueEmpty(LinkQueue *q)
{
	return q->front == q->rear;
}
Status Push(LinkQueue *q, ElemType e)
{
	Qnode * temp = (Qnode *)malloc(sizeof(Qnode));
	if (!temp)
		return ERROR;
	temp->data = e;
	temp->next = NULL;
	q->rear->next = temp;
	q->rear = temp;
	return OK;
}
Status Pop(LinkQueue *q, ElemType *e)
{
	Qnode *temp;
	if (QueueEmpty(q))
		return ERROR;
	temp = q->front->next;  //带头结点,q->front->next 才是值
	*e = temp->data;
	q->front->next = temp->next;
	if (q->rear == temp)
		q->rear = q->front;
	free(temp);
	return OK;
}
int main()
{
	LinkQueue *q;
	InitQueue(q);
	for (int i = 1;i <= 9;i++)
		Push(q, i);
	for (int i = 1;i <= 9;i++) { //顺序输出
		ElemType temp;
		Pop(q, &temp);
		cout << temp << ' ';
	}
	cout << endl;
	system("pause");
	return 0;
}