一般的数据结构书中的栈和队列的实现都是用C语言的代码作为指导,C++则相对较少,所以在学习的过程中我尝试用C++写了一下,如果有错误希望大家能够指出。
#include <iostream>
#include <stdlib.h>
typedef int ElemType;
const int MAXSIZE = 100;
class SqStack {
public:
SqStack();
~SqStack();
void InitStack(SqStack* S);
void ClearStack(SqStack* S);
bool StackEmpty(SqStack S);
void GetTop(SqStack S, ElemType* e);
void Push(SqStack* S, ElemType e);
void Pop(SqStack* S, ElemType* e);
int StackLength(SqStack S);
int top;
ElemType data[MAXSIZE];
};
SqStack::SqStack() {
}
SqStack::~SqStack() {
}
void SqStack::InitStack(SqStack* S) {
S->top = -1;
}
void SqStack::ClearStack(SqStack* S) {
S->top = -1;
}
bool SqStack::StackEmpty(SqStack S) {
if (S.top == -1)return 1;
else if (S.top >= 0)return 0;
else if (S.top < -1) {
std::cout << "栈头指针异常";
return 0;
}
}
void SqStack::GetTop(SqStack S, ElemType* e) {
if (S.top == -1) {
std::cout << "栈空!";
return;
}
*e = S.data[S.top];
}
void SqStack::Push(SqStack* S, ElemType e) {
if (S->top == MAXSIZE - 1) {
std::cout << "栈满!";
return;
}
S->data[S->top + 1] = e;
S->top++;
}
void SqStack::Pop(SqStack* S, ElemType* e) {
if (S->top == -1) {
std::cout << "栈空!";
return;
}
*e = S->data[S->top];
S->top--;
}
int SqStack::StackLength(SqStack S) {
return S.top + 1;
}
int main() {
int demo[10] = { 0 };
for (int i = 0; i < 10; i++)
std::cin >> demo[i];
SqStack* S = new SqStack();
S->InitStack(S);
for (int i = 0; i < 10; i++)
S->Push(S, demo[i]);
int e = 0;
for (int i = 0; i < 10; i++) {
S->Pop(S, &e);
std::cout << e << " ";
}
system("pause");
delete S;
return 0;
}
运行结果: