資料結構之棧的C++程式碼實現
阿新 • • 發佈:2021-01-31
一般的資料結構書中的棧和佇列的實現都是用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;
}
執行結果: