从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
}
相关推荐
Fanxt_Ja11 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后12312 小时前
【数据结构】二叉树的概念
数据结构·二叉树
散1121 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19431 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww1 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚1 天前
[数据结构] 排序
数据结构
睡不醒的kun1 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌1 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long1 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn1 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap