명품C++프로그래밍
명품 C++ Programming 실습문제 7장 11번
anycoding
2021. 5. 21. 00:53
반응형
문제
스택 클래스 Stack을 만들고 푸시(push)용으로 << 연산자를, 팝(pop)을 위해 >> 연산자를, 비어 있는 스택인지를 알기 위해 ! 연산자를 작성하라. 다음 코드를 main()으로 작성하라.
int main()
{
Stack stack;
stack << 3 << 5 << 10; // 3, 5, 10을 순서대로 푸시
while (true) {
if (!stack)break; // 스택 empty
int x;
stack >> x; // 스택의 탑에 있는 정수 팝
cout << x << ' ';
}
cout << endl;
}
결과
10 5 3
스택이란?
스택은 자료구조 중에 하나로서, 후입선출(LIFO : Last-In First-Out)구조이다. 데이터가 들어간 순서의 역순이 나오는 순서이다.
하나의 스택 | 스택 입력(B) | 스택 입력(C) | 스택 삭제(C) |
C | |||
B | B | B | |
A | A | A | A |
소스코드(friend 함수 구현)
#include<iostream>
using namespace std;
class Stack {
int stack[10];
int top;
public:
Stack() { top = -1; }
friend bool operator!(Stack& sta);
friend Stack& operator<<(Stack& sta, int n);
friend void operator>>(Stack& sta, int& n);
};
bool operator!(Stack& sta)
{
if (sta.top == -1)
return true;
return false;
}
Stack& operator<<(Stack& sta, int n)
{
sta.stack[++sta.top] = n;
return sta;
}
void operator>>(Stack& sta, int& n)
{
n = sta.stack[sta.top--];
}
int main()
{
Stack stack;
stack << 3 << 5 << 10; // 3, 5, 10을 순서대로 푸시
while (true) {
if (!stack)break; // 스택 empty
int x;
stack >> x; // 스택의 탑에 있는 정수 팝
cout << x << ' ';
}
cout << endl;
}
반응형