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

一、建立栈

#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;

}

相关推荐
浅念-6 小时前
递归解题指南:LeetCode经典题全解析
数据结构·算法·leetcode·职场和发展·排序算法·深度优先·递归
Kiling_07047 小时前
Java集合进阶:Set与Collections详解
算法·哈希算法
智者知已应修善业7 小时前
【51单片机89C51及74LS273、74LS244组成】2022-5-28
c++·经验分享·笔记·算法·51单片机
洛水水7 小时前
【力扣100题】33.验证二叉搜索树
算法·leetcode·职场和发展
SimpleLearingAI8 小时前
聚类算法详解
算法·数据挖掘·聚类
刀法如飞8 小时前
Go 字符串查找的 20 种实现方式,用不同思路解决问题
算法·面试·程序员
Dlrb121110 小时前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora10 小时前
Python 算法基础篇之集合
python·算法
平行侠10 小时前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
阿旭超级学得完12 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表