【数据结构/C++】栈和队列_链队列

cpp 复制代码
#include <iostream>
using namespace std;
// 链队列
typedef int ElemType;
typedef struct LinkNode
{
  ElemType data;
  struct LinkNode *next;
} LinkNode;
typedef struct
{
  LinkNode *front, *rear;
} LinkQueue;
// 初始化
void InitQueue(LinkQueue &Q)
{
  Q.front = Q.rear = (LinkNode *)malloc(sizeof(LinkNode));
  Q.front->next = NULL;
}
// 入队
bool EnQueue(LinkQueue &Q, ElemType x)
{
  LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
  p->data = x;
  p->next = NULL;
  Q.rear->next = p;
  Q.rear = p;
  return true;
}
// 出队
bool DeQueue(LinkQueue &Q, ElemType &x)
{
  if (Q.front == Q.rear)
  {
    return false;
  }
  LinkNode *p = Q.front->next;
  x = p->data;
  Q.front->next = p->next;
  // 如果是最后一个结点出队
  if (Q.rear == p)
  {
    Q.rear = Q.front;
  }
  free(p);
  return true;
}
// 遍历
void Traverse(LinkQueue Q)
{
  LinkNode *p = Q.front->next;
  while (p != NULL)
  {
    cout << p->data << " ";
    p = p->next;
  }
  cout << endl;
}
// 长度
int QueueLength(LinkQueue Q)
{
  int length = 0;
  LinkNode *p = Q.front->next;
  while (p != NULL)
  {
    length++;
    p = p->next;
  }
  return length;
}
int main()
{
  LinkQueue Q;
  ElemType x;
  InitQueue(Q);
  EnQueue(Q, 1);
  EnQueue(Q, 2);
  EnQueue(Q, 3);
  EnQueue(Q, 4);
  DeQueue(Q, x);
  Traverse(Q);
  cout << QueueLength(Q) << endl;
  return 0;
}
相关推荐
云上漫步者18 小时前
深度实战:Rust交叉编译适配OpenHarmony PC——sys_locale完整适配案例
开发语言·后端·rust
guygg8818 小时前
基于MATLAB的精密星历内插实现方案
开发语言·matlab
专注VB编程开发20年18 小时前
c#语法和java相差多少
java·开发语言·microsoft·c#
cici1587418 小时前
MATLAB中实现图像超分辨率
开发语言·matlab
kaikaile199518 小时前
基于 MATLAB 实现 近红外光谱(NIRS)血液定量分析
开发语言·matlab
爱装代码的小瓶子18 小时前
【c++进阶】在c++11之前的编译器的努力
开发语言·c++·vscode·visualstudio·编辑器·vim
蜗牛love天空18 小时前
vs的运行库区别,静态连接mt和动态链接md运行库
c++
超级大福宝18 小时前
C++ 中 unordered_map 的 at() 和 []
数据结构·c++
蜗牛love天空18 小时前
智能指针的值传递和引用传递
开发语言·c++
☆cwlulu18 小时前
C语言关键字详解
开发语言