【数据结构/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;
}
相关推荐
Charles_go1 分钟前
C#中级8、什么是缓存
开发语言·缓存·c#
残影飞雪7 分钟前
Jetson版本下Pytorch和torchvision
c++
松涛和鸣1 小时前
14、C 语言进阶:函数指针、typedef、二级指针、const 指针
c语言·开发语言·算法·排序算法·学习方法
星期天23 小时前
3.0 C语⾔内存函数:memcpy memmove memset memcmp 数据在内存中的存储:整数在内存中的存储 ⼤⼩端字节序和字节序判断
c语言·数据结构·进阶·内存函数·数据内存存储
智商低情商凑5 小时前
Go学习之 - Goroutines和channels
开发语言·学习·golang
半桶水专家5 小时前
Go 语言时间处理(time 包)详解
开发语言·后端·golang
编程点滴5 小时前
Go 重试机制终极指南:基于 go-retry 打造可靠容错系统
开发语言·后端·golang
实心儿儿5 小时前
C++ —— 模板进阶
开发语言·c++
萧鼎6 小时前
Python PyTesseract OCR :从基础到项目实战
开发语言·python·ocr
go_bai6 小时前
Linux-线程2
linux·c++·经验分享·笔记·学习方法