从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
}
相关推荐
云泽8087 小时前
数据结构之单链表和环形链表的应用(二)-
数据结构
dragoooon348 小时前
[优选算法专题二滑动窗口——串联所有单词的子串]
数据结构·c++·学习·算法·leetcode·学习方法
阿让啊16 小时前
C语言strtol 函数使用方法
c语言·数据结构·c++·单片机·嵌入式硬件
superlls19 小时前
(算法 哈希表)【LeetCode 349】两个数组的交集 思路笔记自留
java·数据结构·算法
Ripple1231220 小时前
数据结构:顺序表与链表
数据结构·链表
一个响当当的名号21 小时前
B树,B+树,B*树(无代码)
数据结构·b树
古译汉书1 天前
嵌入式铁头山羊stm32-ADC实现定时器触发的注入序列的单通道转换-Day26
开发语言·数据结构·stm32·单片机·嵌入式硬件·算法
野犬寒鸦1 天前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode
GalaxyPokemon1 天前
LeetCode - 1089. 复写零
数据结构
失散131 天前
分布式专题——1.2 Redis7核心数据结构
java·数据结构·redis·分布式·架构