当前位置: 首页 > news >正文

C++学习笔记(33)

三十五、栈
示例:
#include <iostream>
using namespace std;
typedef int ElemType; // 自定义链栈的数据元素为整数。
struct SNode // 链栈的结点。
{
ElemType data; // 存放结点的数据元素。
struct SNode* next; // 指向下一个结点的指针。
};
// 初始化链栈,返回值:失败返回 nullptr,成功返回头结点的地址。
SNode* InitStack()
{
SNode* head = new (std::nothrow) SNode; // 分配头结点。
if (head == nullptr) return nullptr; // 内存不足,返回失败。
head->next = nullptr; // 头结点的下一结点暂时不存在,置空。
return head; // 返回头结点。
}
// 销毁链栈。
void DestroyStack(SNode* head)
{
// 销毁链栈是指释放链栈全部的结点,包括头结点。
SNode* tmp;
while (head != nullptr)
{
tmp = head->next; // tmp 保存下一结点的地址。
delete head; // 释放当前结点。
head = tmp; // 指针移动到下一结点。
}
}
// 元素入栈,返回值:false-失败;true-成功。
bool Push(SNode* head, const ElemType& ee)
{
if (head == nullptr) { cout << "链栈不存在。\n"; return false; }
SNode* tmp = new (std::nothrow) SNode; // 分配一个新结点。
if (tmp == nullptr) return false;
tmp->data = ee; // 把元素的值存入新结点。
// 处理 next 指针。
tmp->next = head->next;
head->next = tmp;
return true;
}
// 显示链栈中全部的元素。
void PrintStack(const SNode* head)
{
if (head == nullptr) { cout << "链栈不存在。\n"; return; }
SNode* pp = head->next; // 从第 1 个结点开始。
while (pp != nullptr)
{
cout << pp->data << " "; // 如果元素为结构体,这行代码要修改。
pp = pp->next; // 指针往后移动一个结点。
}
cout << endl;
}
// 求链栈的长度,返回值:>=0-栈 SS 结点的个数。
size_t StackLength(SNode* head)
{
if (head == nullptr) { cout << "链栈不存在。\n"; return 0; }
SNode* pp = head->next; // 头结点不算,从第 1 个结点开始。
size_t length = 0;
while (pp != nullptr) { pp = pp->next; length++; }
return length;
}
// 元素出栈。
bool Pop(SNode* head,ElemType &ee)
{
if (head == nullptr) { cout << "链栈不存在。\n"; return false; }
if (head->next == nullptr) { cout << "链栈为空,没有结点。\n"; return false; }
SNode* pp = head->next; // pp 指向第一个节点。
head->next = head->next->next; // 修改头结点的 next 指针。
ee = pp->data;
delete pp; // 删除第一个节点。
return true;
}
int main()
{
SNode* SS = InitStack(); // 初始化链栈 SS。
cout << "入栈三个元素(1、2、3)。\n";
Push(SS, 1);
Push(SS, 2);
Push(SS, 3);
PrintStack(SS); // 把链栈中全部的元素显示出来。
cout << "链栈的长度:" << StackLength(SS) << endl;
// 元素出栈。
ElemType ee;
Pop(SS,ee);
cout << "出栈的元素的值是:" << ee << endl;
DestroyStack(SS); // 销毁链栈 SS。
}
 

http://www.lryc.cn/news/441452.html

相关文章:

  • 智谱清影 -CogVideoX-2b-部署与使用,带你揭秘生成6s视频的极致体验!
  • 探索Java中的设计模式:原则与实例
  • 【Java】关键字-static【主线学习笔记】
  • 数字自然资源领域的实现路径
  • GitLab邮箱发送邮件:如何实现自动化发信?
  • sqli-labs靶场搭建
  • Leetcode Hot 100刷题记录 -Day14(矩阵置0)
  • 每日刷题(算法)
  • 大牛直播SDK核心音视频模块探究
  • gin配置swagger文档
  • 基于ssm的快餐店点餐系统设计与实现
  • 集合框架底层使用了什么数据结构
  • Activiti7《第二式:破剑式》——工作流中的以柔克刚
  • docker快速搭建kafka
  • 基于 onsemi NCV78343 NCV78964的汽车矩阵式大灯方案
  • OpenAl o1论文:Let’s Verify Step by Step 快速解读
  • Errorresponsefromdaemon:toomanyrequests:Youhavereachedyourpullratelimit.
  • [2025]医院健康陪诊系统(源码+定制+服务)
  • Golang | Leetcode Golang题解之第405题数字转换为十六进制数
  • VB中如何使用正则表达式(Regular Expressions)
  • Docker FROM 指定基础镜像
  • 19:I2C一:程序模拟I2C通信时序
  • 最佳实践 · MySQL 分区表实战指南
  • 详细介绍 Redis 列表的应用场景
  • 游戏如何检测加速外挂
  • 【STM32 HAL库】OLED显示模块
  • Redis---卸载Redis
  • 《C++模板元编程实战》阅读记录
  • pybind11 学习笔记
  • 36.贪心算法3