从0开始的数据结构的书写-------线性表(栈)

(复习考研的休息区,心血来潮,写点代码)

三个规则:

1、不使用c++ stl库进行书写

2、最好基于严蔚敏老师的数据结构

3、最好使用malloc和realloc动态分配内存

(如果有问题或者是有没有实现的操作,请大家提出来)

cpp 复制代码
#include<iostream>
#include<cstring>

using namespace std;

const int INF = 0x3f3f3f3f3f;
#define N 100
#define offset 10

typedef struct
{
	int *base;
	int *top; // 永远指在第一个元素的上方 
	int size;
}SqStack;

void InitStack(SqStack &S)
{
	S.base = (int *)malloc(N * sizeof(int));
	S.top = S.base;
	S.size = N;
}

int GetTop(SqStack &S)
{
	if(S.top == S.base) return INF;
	return *(S.top - 1);
}

void Push(SqStack &S , int e)
{
	if(S.top - S.base >= S.size)
	{
		S.base = (int *)realloc(S.base , (S.size + offset) * sizeof(int));
		S.top = S.base + S.size;
		S.size += offset;
	}
	*S.top = e;
	S.top ++;
}

int Pop(SqStack &S)
{
	if(S.top == S.base) return INF;
	return * --S.top;
}

int main()
{
	SqStack s;
	InitStack(s);
	
	for(int i = 1;i <= 10;i ++)
		Push(s , i); // 最后从底向上的序列是1、2、3、4、5、6、7、8、9、10
	
	cout << "当前弹出的是:" << Pop(s) << endl; // 10
	cout << "当前弹出的是:" << Pop(s) << endl; // 9
	cout << "当前弹出的是:" << Pop(s) << endl; // 8
}
相关推荐
梦帮科技9 小时前
vLLM / TensorRT-LLM 极限推理:PagedAttention 细粒度物理页表管理与连续批处理(Continuous Batching)实战
数据结构·人工智能·分布式·python·深度学习·算法·vllm
H.莓飛11 小时前
【数据结构】链表_OJ题
linux·数据结构·算法·链表
All for pursuit.12 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
7yewh14 小时前
SLAM 从视觉里程计到建图(6)
数据结构·人工智能·机器人·自动驾驶·嵌入式
程序员清风15 小时前
pandas 核心数据结构:Series 与 DataFrame
数据结构·pandas
All for pursuit.15 小时前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
_wxd66616 小时前
C++STL map与set
数据结构·c++
mmmmath_316 小时前
LeetCode.150.逆波兰表达式求值
数据结构
漂流瓶jz17 小时前
UVA-1610 聚会游戏 题解答案代码 算法竞赛入门经典第二版
数据结构·c++·算法·题解·aoapc·算法竞赛入门经典·uva
imDwAaY17 小时前
Redis Set 如何节省内存?从整数集合到哈希表的设计取舍
数据结构·redis·散列表