【数据结构/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;
}
相关推荐
Echo``5 分钟前
2:QT联合HALCON编程—图像显示放大缩小
开发语言·c++·图像处理·qt·算法
Felven30 分钟前
A. Ideal Generator
java·数据结构·算法
JAVA学习通1 小时前
JAVA多线程(8.0)
java·开发语言
Luck_ff08101 小时前
【Python爬虫详解】第四篇:使用解析库提取网页数据——BeautifuSoup
开发语言·爬虫·python
学渣676561 小时前
什么时候使用Python 虚拟环境(venv)而不用conda
开发语言·python·conda
How_doyou_do1 小时前
树状数组底层逻辑探讨 / 模版代码-P3374-P3368
数据结构·算法·树状数组
想睡hhh1 小时前
c++STL——stack、queue、priority_queue的模拟实现
开发语言·c++·stl
小鹿鹿啊1 小时前
C语言编程--14.电话号码的字母组合
c语言·开发语言·算法
Sunlight_7771 小时前
第六章 QT基础:6、QT的Qt 时钟编程
开发语言·qt·命令模式
cloues break.1 小时前
C++初阶----模板初阶
java·开发语言·c++