数据结构——用数组实现栈(十七)

一、建立栈

#define NUM 10

struct Node

{

int arrNUM;

int index;

};

  • int arr[NUM]:固定长度的整型数组,数组大小由宏NUM决定(10个元素)

  • int index:可用于记录数组当前有效元素的索引位置或其他用途

struct Node* Stack()//创建头

{

struct Node* pT = (struct Node*)malloc(sizeof(struct Node));

if (NULL == pT)

return NULL;

pT->index = 0;

return pT;

}

  • 动态内存分配 :使用malloc为头节点分配内存,需检查分配是否成功(NULL == pT)。

  • 初始化成员 :将头节点的index字段初始化为0,通常表示空栈或基础索引。

  • 返回类型 :函数返回struct Node*类型指针,失败时返回NULL

调用时需检查返回值是否为NULL,避免空指针操作。

二、添加元素

void Push(struct Node* pStack, int a)//添加元素

{

if (NULL == pStack || NUM <= pStack->index)

return;

pStack->arrpStack-\>index = a;

pStack->index++;

}

  1. 检查指针有效性

    通过条件 NULL == pStack 判断传入的栈指针是否为空。如果为空,直接返回,避免空指针解引用。

  2. 检查栈是否已满

    通过条件 NUM <= pStack->index 判断栈是否已满。NUM 可能是预定义的栈容量常量。如果栈已满,直接返回,避免数组越界。

  3. 压入元素

    将值 a 存入栈顶位置 pStack->arr[pStack->index]

  4. 更新栈顶指针

    通过 pStack->index++ 将栈顶指针后移一位,指向下一个空闲位置。

调用

Push(pStack, arr0);

Push(pStack, arr1);

Push(pStack, arr2);

Push(pStack, arr3);

三、翻转数组及释放

判断栈是否为空

bool IsEmpty(struct Node* pStack)//判断栈是否为空

{

if (NULL == pStack || 0 == pStack->index)

return true;

return false;

}

该函数接受一个指向栈顶节点的指针pStack作为参数

当满足以下任一条件时返回true

  • 栈顶指针为NULL(表示栈不存在或未初始化)
  • 栈的索引值index为0(表示栈中没有元素)

否则返回false,表示栈不为空

删除当前尾节点

void Pop(struct Node* pStack)

{

if (IsEmpty(pStack))

return ;

pStack->index -= 1;

}

  • 调用 IsEmpty 函数检查栈是否为空。若为空(IsEmpty 返回 true),直接返回,避免非法操作。不是空就pStack->index -= 1删除当前尾节点
获取当前尾节点

int Top(struct Node* pStack)

{

if (IsEmpty(pStack))

return 0;

return pStack->arrpStack-\>index - 1;

}

调用 IsEmpty 函数检查栈是否为空。若为空(IsEmpty 返回 true),直接返回,避免非法操作。不是空就返回获取当前尾节点。

调用

arr0 = Top(pStack);

Pop(pStack);

arr1 = Top(pStack);

Pop(pStack);

arr2 = Top(pStack);

Pop(pStack);

arr3 = Top(pStack);

Pop(pStack);

释放头节点

void FreeStack(struct Node** pStack)

{

free(*pStack);

*pStack = NULL;

}

相关推荐
Jerry2 小时前
LeetCode 101. 对称二叉树
算法
可编程芯片开发4 小时前
基于MPPT最大功率跟踪的离网光伏发电系统Simulink建模与仿真
算法
AI科技星4 小时前
线性算子不是空间映射函数,是全域双螺旋场之间拉伸、旋转、耦合、坍缩的跨空间标准化变换载体《全域数学vs传统数学:人类文明进阶200讲》第80讲
线性代数·算法·矩阵·数据挖掘·回归·乖乖数学·全域数学
米罗篮4 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
dream_home84074 小时前
图像算法模型NPU适配与算法服务实战指南
人工智能·python·算法·npu 图像服务
大鱼>5 小时前
多宠物家庭智能管理平台:云端架构与多设备协同实战
python·算法·iot·宠物
To_OC5 小时前
LC 22 括号生成:刷完这道题,我终于搞懂回溯剪枝了
javascript·算法·leetcode
To_OC5 小时前
LC 39 组合总和:回溯入门必刷题,我踩过的两个坑都在这了
javascript·算法·leetcode
数字杂技师6 小时前
每条推荐都很准,为什么我还是越刷越无聊?
算法
兰令水6 小时前
hot100【acm版】【2026.7.14打卡-java版本】
java·数据结构·算法·leetcode·面试