一般的数据结构书中的栈和队列的实现都是用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;
}

运行结果:
输入一串整型数 依次入栈 然后依次出栈 打印

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐