C++

5장 실습문제_5번

림가이드 2020. 12. 24. 17:08

5. 다음과 같이 선언된 정수를 저장하는 스택 클래스 MyIntStack을 구현하라. MyIntStack 스택에 저장할 수 있는 정수의 최대 개수는 10개이다.

class MyIntStack {
	int p[10];
	int tos;
public:
	MyIntStack();
	bool push(int n);
	bool pop(int& n);
};

int main() {
	MyIntStack a;
	for (int i = 0; i < 11; i++) {
		if (a.push(i))
			cout << i << ' ';
		else
			cout << endl << i + 1 << " 번째 stack full" << endl;
	}
	int n;
	for (int i = 0; i < 11; i++) {
		if (a.pop(n))
			cout << n << ' ';
		else
			cout << endl << i + 1 << " 번째 stack empty";
	}
	cout << endl;
}

 

 

 

-답

#include <iostream>
using namespace std;

class MyIntStack {
	int p[10];
	int tos;
public:
	MyIntStack() { tos = 0; }
	bool push(int n);
	bool pop(int& n);
};

bool MyIntStack::push(int n) {
	if (tos < 10) {
		p[tos] = n;
		tos++;
		return true;
	}
	else 
		return false;
}

bool MyIntStack::pop(int& n) {
	tos--;
	if (tos < 0) 
		return false;
	else {
		n = p[tos];
		return true;
	}
}

int main() {
	MyIntStack a;
	for (int i = 0; i < 11; i++) {
		if (a.push(i))
			cout << i << ' ';
		else
			cout << endl << i + 1 << " 번째 stack full" << endl;
	}
	int n;
	for (int i = 0; i < 11; i++) {
		if (a.pop(n))
			cout << n << ' ';
		else
			cout << endl << i + 1 << " 번째 stack empty";
	}
	cout << endl;
}