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

一、建立栈

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

}

相关推荐
y1su6 分钟前
Leetcode 动态规划 模板
java·数据结构·算法·leetcode·动态规划
All for pursuit.1 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
MoRanzhi12031 小时前
106.正则问题(分治)
python·算法·正则表达式·蓝桥杯·递归·分治算法·字符串处理
suhan2 小时前
【数据结构】五、树:7.哈夫曼树、哈夫曼编码
数据结构·算法·排序算法
kkhimself2 小时前
POJ-3126
算法
suhan2 小时前
【数据结构】五、树:6.平衡二叉树AVL
数据结构·算法·排序算法
suhan2 小时前
【数据结构】五、树:5.二叉排序树BST
数据结构·算法·排序算法
爱读书的小胖2 小时前
80. 删除有序数组中的重复项 II
java·数据结构·算法
臻选云栗子3 小时前
PCDN跑不起来?先别甩锅给平台,问题可能出在这
算法·程序员
小画家~3 小时前
vue3 里面的 itemList.reduce
前端·数据结构·算法