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

一、建立栈

#define NUM 10

struct Node

{

int arr[NUM];

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->arr[pStack->index] = a;

pStack->index++;

}

  1. 检查指针有效性

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

  2. 检查栈是否已满

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

  3. 压入元素

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

  4. 更新栈顶指针

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

调用

Push(pStack, arr[0]);

Push(pStack, arr[1]);

Push(pStack, arr[2]);

Push(pStack, arr[3]);

三、翻转数组及释放

判断栈是否为空

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->arr[pStack->index - 1];

}

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

调用

arr[0] = Top(pStack);

Pop(pStack);

arr[1] = Top(pStack);

Pop(pStack);

arr[2] = Top(pStack);

Pop(pStack);

arr[3] = Top(pStack);

Pop(pStack);

释放头节点

void FreeStack(struct Node** pStack)

{

free(*pStack);

*pStack = NULL;

}

相关推荐
zyq99101_11 小时前
优化二分查找:前缀和降复杂度
数据结构·python·蓝桥杯
qyzm1 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
逆境不可逃1 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
CoderCodingNo2 小时前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法
放下华子我只抽RuiKe52 小时前
机器学习全景指南-直觉篇——基于距离的 K-近邻 (KNN) 算法
人工智能·gpt·算法·机器学习·语言模型·chatgpt·ai编程
kisshuan123962 小时前
[特殊字符]【深度学习】DA3METRIC-LARGE单目深度估计算法详解
人工智能·深度学习·算法
sali-tec2 小时前
C# 基于OpenCv的视觉工作流-章33-Blod分析
图像处理·人工智能·opencv·算法·计算机视觉
Eward-an3 小时前
LeetCode 239. 滑动窗口最大值(详细技术解析)
python·算法·leetcode
一叶落4383 小时前
LeetCode 50. Pow(x, n)(快速幂详解 | C语言实现)
c语言·算法·leetcode
皙然3 小时前
彻底吃透红黑树
数据结构·算法