顺序栈的结构有两种实现方式,第一种方式为:
typedef struct _stack {
int top;
datatype* base;
}sqlStack;
这种方式只需要申请一个指针base,top用整数表示,简洁明了,第二种方式采用了两个指针
typedef struct _stack {
datatype* top;
datatype* base;
}sqlStack;
下面用第一种方式实现,完整的代码如下:
#include<Windows.h>
#include<iostream>
using namespace std;
#define MAX_SIZE 100
typedef int datatype;
typedef struct _stack {
int top;
datatype* base;
}sqlStack;
bool initStack(sqlStack& stack);
bool popStack(sqlStack& stack, datatype& value);
bool pushStack(sqlStack& stack, datatype value);
bool isFull(sqlStack& stack);
bool isEmpty(sqlStack& stack);
bool getTop(sqlStack& stack, datatype& value);
void destroy(sqlStack& stack);
int main() {
sqlStack stack;
initStack(stack);
int value;
for (int i = 0; i < 5; i++) {
pushStack(stack, i + 5);
getTop(stack, value);
cout << "入栈的元素:" << value << endl;
}
cout << "再进行出栈,元素如下" << endl;
while (stack.top) {
popStack(stack, value);
cout << value << " ";
}
system("pause");
destroy(stack);
return 0;
}
bool initStack(sqlStack& stack) {
stack.base = new datatype[MAX_SIZE];
if (!stack.base) return false;
stack.top = 0;
return true;
}
bool popStack(sqlStack& stack, datatype& value) {
if (isEmpty(stack)) return false;
value = stack.base[--stack.top];
return true;
}
bool pushStack(sqlStack& stack, datatype value) {
if (isFull(stack)) return false;
stack.base[stack.top++] = value;
return true;
}
bool isFull(sqlStack& stack) {
if (stack.top == MAX_SIZE)
return true;
else
return false;
}
bool isEmpty(sqlStack& stack) {
if (!stack.top)
return true;
else
return false;
}
bool getTop(sqlStack& stack, datatype& value) {
if (isEmpty(stack)) return false;
value = stack.base[stack.top - 1];
return true;
}
void destroy(sqlStack& stack) {
if (stack.base)
delete[]stack.base;
}