【数据结构/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;
}
相关推荐
froginwe1115 小时前
Python 3 输入和输出
开发语言
小何好运暴富开心幸福15 小时前
C++之再谈类与对象
开发语言·c++·vscode
zhangfeng113315 小时前
R 导出 PDF 时中文不显示 不依赖 showtext** 的最简方案(用 extrafont 把系统 TTF 真正灌进 PDF 内核)
开发语言·r语言·pdf·生物信息
应用市场15 小时前
自建本地DNS过滤系统:实现局域网广告和垃圾网站屏蔽
开发语言·php
郝学胜-神的一滴15 小时前
中秋特别篇:使用QtOpenGL和着色器绘制星空与满月
开发语言·c++·算法·软件工程·着色器·中秋
Predestination王瀞潞16 小时前
Python oct() 函数
开发语言·python
生物小卡拉16 小时前
R脚本--PCA分析系列1_v1.0
开发语言·r语言
生物小卡拉16 小时前
R脚本——LefSE分析与可视化-v1
开发语言·r语言
fl17683116 小时前
基于python+tkinter实现的自动组卷评卷考试系统python源码+课程设计+项目说明
开发语言·python·课程设计