数据结构-链队列操作实践
数据结构-链队列操作实践
编写函数,采用链式存储实现队列的初始化、入队、出队操作
#include<iostream>
#include<malloc.h>
using namespace std;
// 链队列结点类型定义
typedef struct LinkNode {
int data;
struct LinkNode* next;
}LinkNode;
// 链队列类型定义
typedef struct {
LinkNode* front, * rear; // 头指针、尾指针
}LinkQueue;
/** * 初始化链队列 * @param Q 链队列Q */
void InitQueue(LinkQueue& Q) {
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
if(Q.front && Q.rear)
Q.front->next = NULL; // 初始为空
}
/** * 入队 * @param Q 链队列Q * @param x 入队元素 */
void EnQueue(LinkQueue& Q, int x) {
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
if (s) {
s->data = x;
s->next = NULL; // 创建新结点
Q.rear->next = s; // 插入到链尾
Q.rear = s; // rear指向新的尾结点
}
}
/** * 出队 * @param Q 队列Q * @param x 通过x返回出队元素 * @return 出队成功为真,否则为假 */
bool DeQueue(LinkQueue& Q, int& x) {
if (Q.front == Q.rear) // 空队
return false;
LinkNode* p = Q.front->next; // 从队头出队,即开始结点
x = p->data;
Q.front->next = p->next; // 头指针的next指向下一个结点
if (Q.rear == p)
Q.rear = Q.front; // 若原队列中只有一个结点,删除后变空,防止尾指针丢了
free(p);
return true;
}
int main() {
int n; // 入队n个元素
cin >> n;
// 初始化链队列
LinkQueue Q;
InitQueue(Q);
int x;
// 链队列入队
cout << "入队:";
for (int i = 0; i < n; i++)
{
cin >> x;
EnQueue(Q, x);
}
// 链队列出队
cout << "出队:";
for (int i = 0; i < n; i++)
{
if (DeQueue(Q, x))
cout << x << " ";
}
cout << endl;
return 0;
}
创作不易,喜欢的话加个关注,点个赞,谢谢谢谢谢谢谢!