数据结构:链式存储结构的队列,链队列
队列的链式存储结构是单链表,只能在尾部插入和在头部删除
头指针指向头节点,尾指针指向最后一个节点
空队列时,头指针和尾指针都指向头节点
#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
typedef int QElemType;
typedef int Status;
/* 节点结构 */
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode,*Queueptr;
/* 链表结构
* 头指针指向头节点,尾指针指向最后一个节点
* 链队列空的条件:front和rear都指向头节点
*/
typedef struct
{
Queueptr front, rear;
}LinkQueue;
/* 链队列的初始化:InitQueue
* 需要将front指向头节点
* 初始还有输入带数据域的节点,则rear=front
*/
Status InitQueue(LinkQueue *Q, Queueptr p)
{
Q->front = p;
Q->rear = Q->front ;
return OK;
}
/* 链队列入队操作:在链表尾部插入节点,EnQueue
* 思路:
* 1、新建一个节点s并初始化,并判断是否内存分配成功
* 2、s->data=e;s->next=NULL;
* 3、将原最后一个节点的next指向新节点:Q->rear->next=s;
* 4、将rear指向新节点
*/
Status EnQueue(LinkQueue *Q, QElemType e)
{
Queueptr s;
s = (Queueptr)malloc(sizeof(QNode));
if (!s)
{
cout << "内存分配不成功" << endl;
return ERROR;
}
s->data = e;
s->next = NULL;
Q->rear->next = s;
Q->rear = s;
return OK;
}
/* 链队列出队操作:在链表头部删除第一个节点,DeQueue
* 思路:
* 1、判断链队列是否为空:Q->front==Q->rear
* 2、判断若只剩一个节点条件:Q->rear == p
* 3、2成立:声明节点p,p=Q->front->next,e=p->data,Q->front->next=p->next,并将rear指向头节点,释放p
* 3、2不成立:声明节点p,p=Q->front->next,e=p->data,Q->front->next=p->next,释放p
* 4、综合2和3
*/
Status DeQueue(LinkQueue *Q, QElemType *e)
{
if (Q->front == Q->rear)
{
cout << "链队列为空" << endl;
return ERROR;
}
Queueptr p;
p = Q->front->next;
*e = p->data;
Q->front->next = p->next;
if (Q->rear == p)
{
Q->rear = Q->front;
}
free(p);
return OK;
}
int main()
{
int length;
cout << "输入初始链队列长度:";
cin >> length;
cout << "在链队列中依次入队:";
LinkQueue *Q;
Queueptr p;
Q = (LinkQueue *)malloc(sizeof(LinkQueue));
p = (Queueptr)malloc(sizeof(QNode));
InitQueue(Q,p);
int i,e;
for (i = 0; i < length; i++)
{
cin >> e;
EnQueue(Q, e);
}
cout << "输出需要出队的元素个数:";
cin >> length;
cout << "出队元素依次为:";
for (i = 0; i < length; i++)
{
DeQueue(Q, &e);
cout << e << ' ';
}
cout << '\n';
return OK;
}
结果为: