【数据结构/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;
}
相关推荐
nananaij23 分钟前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
qqxhb31 分钟前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
阿蒙Amon33 分钟前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
无小道35 分钟前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++
爱莉希雅&&&43 分钟前
技术面试题,HR面试题
开发语言·学习·面试
晚云与城1 小时前
【数据结构】顺序表和链表
数据结构·链表
开开心心_Every2 小时前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony
FirstFrost --sy2 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Yingye Zhu(HPXXZYY)3 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
一瓣橙子3 小时前
7.7日 实验03-Spark批处理开发(2)
开发语言·javascript·ajax