栈:是一种只能先进先出的数据结构,通过栈顶和栈底指针控制元素的输入输出。
结构体定义:
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;
}