栈的讲解内容可在B站搜索:源味Cheese
// Stack.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
const int MAX_SIZE = 100;
using namespace std;
typedef struct SqStack {
int data[MAX_SIZE];
int top;
}SqStack;
void InitStack(SqStack*& S) {
S = new SqStack();
S->top = -1;
}
void DestroyStack(SqStack*& S) {
free(S);
}
bool isSqStackEmpty(SqStack* S) {
return (S->top == -1);
}
bool PushStack(SqStack*& S, int data) {
if (S->top == MAX_SIZE - 1) return false;
S->data[++S->top] = data;
//S->top++;
//S->data[S->top] = data;
return true;
}
bool PopStack(SqStack*& S,int &e) {
if (S->top == -1) return false;
e = S->data[S->top--];
return true;
}
int PopStack(SqStack*& S) {
if (S->top == -1) return -1;
S->top--;
}
int GetTop(SqStack* S) {
int e;
if (S->top == -1) {
return false;
}
e = S->data[S->top];
return e;
}
/**
/
bool GetTop(SqStack* S, int& e) {
if (S->top == -1) {
return false;
}
e = S->data[S->top];
return true;
}
/*
void Show(SqStack* S) {
for (int i = 0; i < S->top; i++) {
cout << S->data[i] << " ";
}
cout << endl;
}*/
/*void createSqStack(SqStack*& S, int a[], int n) {
for (int i = 0; i < n; i++) {
PushStack(S, a[i]);
}
}*/
//在栈这种数据结构中,用普通的show方法和create方法似乎都会出现bug,目前还不知道为什么
//在栈结构的ADT中也没有关于show方法和create方法的定义
//那输出栈估计就只能用每一个pop之后在看输出的结果了
bool symmetry(int a[]) {
SqStack* s;
InitStack(s);
int n = sizeof(a) / 4;
int e;
for (int i = 0; i < n; i++) { //在这里计算sizeof(a) / 4 会出答案上的错误 -> 因为出栈之后数组的大小变了
PushStack(s, a[i]);
}
for (int i = 0; i < n; i++) {
e = GetTop(s);
PopStack(s);
if (a[i] != e) {
DestroyStack(s);
return false;
}
}
DestroyStack(s);
return true;
}
int main()
{
int a[] = { 1,2,3,2,1 };
int e;
if (symmetry(a)) cout << "对称" << endl;
else cout << "bu对称" << endl;
}