从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
}
相关推荐
探序基因7 小时前
单细胞Seurat数据结构修改分群信息
数据结构
六义义7 小时前
java基础十二
java·数据结构·算法
张张努力变强10 小时前
C++ 类和对象(四):const成员函数、取地址运算符重载全精讲
开发语言·数据结构·c++·后端
历程里程碑12 小时前
双指针 --- 接雨水
java·数据结构·python·算法·leetcode·职场和发展·tornado
Snow_day.12 小时前
【补题记录】AT441,442
数据结构·算法·贪心算法·动态规划·图论
DLGXY12 小时前
数据结构——栈(十六)
数据结构
Tim_1013 小时前
【算法专题训练】38、二分查找算法
数据结构·算法
weixin_4617694013 小时前
判断是否为素数
数据结构·c++·算法·素数
玉树临风ives14 小时前
atcoder ABC442 题解
数据结构·c++·算法
橘颂TA14 小时前
【剑斩OFFER】算法的暴力美学——力扣 542 .01 题:矩阵
数据结构·c++·算法·leetcode·职场和发展·哈希算法·结构与算法