본문 바로가기

언어/C++

5장 5번 - 스택에 데이터 삽입,삭제

#include <iostream>
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class MyIntStack{
	int *p;
	int max=10;
	int top=0;
	int size;
public:
	MyIntStack(){
		p=new int[max];
	}
	~MyIntStack(){
		delete[] p;
	}
	bool push(int n);
	bool pop(int &n);
};

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

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


} 

int main(int argc, char** argv) {
	
	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;
	
	return 0;
}