数据结构---栈

栈:是一种只能先进先出的数据结构,通过栈顶和栈底指针控制元素的输入输出。

结构体定义:

typedef int ElemType;
typedef struct Stack {
	ElemType* top;
	ElemType* base;
}Stack;

初始化:
先分配内存空间
再使栈顶和栈底指向相同,表示空栈

void init(Stack& S) {
	S.top = new ElemType[100];
	if (!S.top)
		return;
	S.base = S.top;
}

是否为空或满::
如果栈顶和栈底指向相同,表示栈为空
如果栈中数据元素等于栈的最大值,那么栈空间已经满。

bool IsEmpty(Stack& S) {
	if (S.base == S.top) {
		return true;
	}
	else {
		return false;
	}
}
bool Isfull(Stack& S) {
	if (S.top - S.base == MAX_SIZE) {
		return true;
	}
	else {
		return false;
	}
}

出栈:
将栈顶元素取出,然后栈的大小-1;
这里先–再复制的原因是,top指针是指向栈顶元素下一个位置的。

bool PopTop(Stack& S, ElemType &e) {
	if (IsEmpty(S)) {
		return  false;
	}
	e = *(--S.top);
	return true;
}

入栈:

bool Push(Stack& S, ElemType e) {
	if(Isfull(S)){
		return false;
	}
	*(S.top) = e;
	S.top++;
	return true;
}

全部代码:

#include<iostream>
#include<Windows.h>
#define MAX_SIZE 100
using namespace std;
typedef int ElemType;
typedef struct Stack {
	ElemType* top;
	ElemType* base;
}Stack;
bool IsEmpty(Stack& S);
bool Isfull(Stack &S);
void init(Stack& S);
bool PopTop(Stack& S, ElemType &e);
bool Push(Stack &S,ElemType e);
bool GetTop(Stack& S, ElemType e);
int main() {
	Stack S;
	init(S);
	for (int i = 0;i < 5;i++) {
		Push(S,i);
	}
	int e;
	while (PopTop(S, e)) {
		cout << e << endl;
	}
	system("pause");
	return 0;
}
void init(Stack& S) {
	S.top = new ElemType[100];
	if (!S.top)
		return;
	S.base = S.top;
}
bool PopTop(Stack& S, ElemType &e) {
	if (IsEmpty(S)) {
		return  false;
	}
	e = *(--S.top);
	return true;
}
bool IsEmpty(Stack& S) {
	if (S.base == S.top) {
		return true;
	}
	else {
		return false;
	}
}
bool Isfull(Stack& S) {
	if (S.top - S.base == MAX_SIZE) {
		return true;
	}
	else {
		return false;
	}
}
bool Push(Stack& S, ElemType e) {
	if(Isfull(S)){
		return false;
	}
	*(S.top) = e;
	S.top++;
	return true;
}
bool GetTop(Stack& S, ElemType e) {
	if (!IsEmpty(S)) {
		return  false;
	}
	e = *(S.top - 1);
	return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值