栈的基础操作源码

栈的讲解内容可在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;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值