반응형
문제 5, 6번에 적용되는 BaseArray 클래스는 다음과 같다.
class BaseArray {
private:
int capacity; // 배열의 크기
int* mem; // 정수 배열을 만들기 위한 메모리의 포인터
protected:
BaseArray(int capacity = 100)
{
this->capacity = capacity; mem = new int[capacity];
}
~BaseArray() { delete[]mem; }
void put(int index, int val) { mem[index] = val; }
int get(int index) { return mem[index]; }
int getCapacity() { return capacity; }
};
문제
BaseArray 클래스를 상속받아 스택으로 작동하는 Mystack 클래스를 작성하라.
int main()
{
MyStack mStack(100);
int n;
cout << "스택에 삽입할 5개의 정수를 입력하라>> ";
for (int i = 0; i < 5; i++)
{
cin >> n;
mStack.push(n); //스택에 푸시
}
cout << "스택용량:" << mStack.capacity() << ", 스택크기:" << mStack.length() << endl;
cout << "스택의 모든 원소를 팝하여 출력한다>> ";
while (mStack.length() != 0) {
cout << mStack.pop() << ' '; //스택에서 팝
}
cout << endl << "스택의 현재 크기 : " << mStack.length() << endl;
}
결과
스택에 삽입할 5개의 정수를 입력하라>>1 3 5 7 9
스택 용량 : 100, 스택 크기 : 5
스택의 모든 원소를 팝하여 출력한다>> 9 7 5 3 1
스택의 현재 크기 : 0
소스코드
#include<iostream>
using namespace std;
class BaseArray {
private:
int capacity; // 배열의 크기
int* mem; // 정수 배열을 만들기 위한 메모리의 포인터
protected:
BaseArray(int capacity = 100)
{
this->capacity = capacity; mem = new int[capacity];
}
~BaseArray() { delete[]mem; }
void put(int index, int val) { mem[index] = val; }
int get(int index) { return mem[index]; }
int getCapacity() { return capacity; }
};
class MyStack : public BaseArray {
int top = -1;
public:
MyStack(int capacity) : BaseArray(capacity) {};
void push(int data);
int capacity();
int length();
int pop();
};
void MyStack::push(int data)
{
if (top >= getCapacity())
{
cout << "스택이 가득차있습니다." << endl;
exit(1);
}
put(++top, data);
}
int MyStack::capacity()
{
return getCapacity();
}
int MyStack::length()
{
return top + 1;
}
int MyStack::pop()
{
if (top <= -1) {
cout << "스택이 비었습니다.." << endl;
exit(1);
}
return get(top--);
}
int main()
{
MyStack mStack(100);
int n;
cout << "스택에 삽입할 5개의 정수를 입력하라>> ";
for (int i = 0; i < 5; i++)
{
cin >> n;
mStack.push(n); //스택에 푸시
}
cout << "스택용량:" << mStack.capacity() << ", 스택크기:" << mStack.length() << endl;
cout << "스택의 모든 원소를 팝하여 출력한다>> ";
while (mStack.length() != 0) {
cout << mStack.pop() << ' '; //스택에서 팝
}
cout << endl << "스택의 현재 크기 : " << mStack.length() << endl;
}
반응형
'명품C++프로그래밍' 카테고리의 다른 글
명품 C++ Programming 실습문제 8장 8번 (1) | 2021.05.26 |
---|---|
명품 C++ Programming 실습문제 8장 7번 (1) | 2021.05.26 |
명품 C++ Programming 실습문제 8장 5번 (2) | 2021.05.22 |
명품 C++ Programming 실습문제 8장 4번 (0) | 2021.05.21 |
명품 C++ Programming 실습문제 8장 3번 (0) | 2021.05.21 |