从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
}
相关推荐
OOJO4 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
田梓燊6 小时前
code 560
数据结构·算法·哈希算法
会编程的土豆7 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
迈巴赫车主8 小时前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯
Kethy__8 小时前
计算机中级-数据库系统工程师-数据结构-查找算法
数据结构·算法·软考·查找算法·计算机中级
所以遗憾是什么呢?8 小时前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
OOJO9 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
茉莉玫瑰花茶9 小时前
数据结构 - 并查集
数据结构
汀、人工智能9 小时前
05 - 函数基础
数据结构·算法·数据库架构·05 - 函数基础
计算机安禾11 小时前
【数据结构与算法】第28篇:平衡二叉树(AVL树)
开发语言·数据结构·数据库·线性代数·算法·矩阵·visual studio