从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
}
相关推荐
tobias.b7 小时前
计算机基础知识-数据结构
java·数据结构·考研
不想看见40410 小时前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
计算机安禾10 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
皮卡狮11 小时前
高阶数据结构:AVL树
数据结构·算法
不要秃头的小孩11 小时前
50. 随机数排序
数据结构·python·算法
故事和你9112 小时前
sdut-python-实验四-python序列结构(21-27)
大数据·开发语言·数据结构·python·算法
丶小鱼丶13 小时前
数据结构和算法之【栈】
java·数据结构
不要秃头的小孩13 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
散峰而望13 小时前
【基础算法】从入门到实战:递归型枚举与回溯剪枝,暴力搜索的初级优化指南
数据结构·c++·后端·算法·机器学习·github·剪枝
elseif12315 小时前
CSP-S提高级大纲
开发语言·数据结构·c++·笔记·算法·大纲·考纲