반응형
스택이란?
- LIFO (Last In First Out) 후입선출 특성을 가지는 자료구조
- 한 쪽 끝에서만 자료를 넣고 뺄 수 있다
스택의 연산
- size() : 현재 스택에 들어있는 데이터 원소의 개수를 반환.
- empty() : 현재 스택이 비어있으면 true, 아닐 경우 false 반환.
- push(x) : 현재 스택에 데이터 x를 삽입.
- pop() : 현재 스택의 가장 위에 있는 데이터 원소를 제거.
- top() : 현재 스택의 가장 위에 있는 데이터 원소를 반환.
스택의 구현
#include <iostream>
using namespace std;
const int MAX = 1e5;
class Stack {
private:
int data[MAX];
int index;
public:
Stack();
int size();
bool empty();
void push(int x);
void pop();
int top();
};
Stack::Stack() { index = -1; }
int Stack::size() { return index + 1; }
bool Stack::empty() {
if (index == -1)
return true;
else
return false;
}
void Stack::push(int x) { data[++index] = x; }
void Stack::pop() { index--; }
int Stack::top() { return data[index]; }
int main() {
Stack s;
cout << "데이터 입력 : \n";
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
cout << "데이터 입력 완료 \n";
cout << "size() : " << s.size() << "\n";
cout << "데이터 출력 : [";
while (!s.empty()) {
if (s.size() == 1)
cout << s.top();
else
cout << s.top() << " ";
s.pop();
}
cout << "]\n";
}
출력 결과
반응형
'알고리즘 > 이론' 카테고리의 다른 글
[알고리즘] 유클리드 호제법 (Euclidean Algorithm) (0) | 2022.01.18 |
---|---|
[자료구조] 덱 - Deque (0) | 2022.01.14 |
[자료구조] 큐 - Queue (0) | 2022.01.14 |
[알고리즘] 동적 프로그래밍 (Dynamic Programming) (0) | 2021.12.27 |
[알고리즘] 탐욕 알고리즘 (Greedy Algorithm) (0) | 2021.12.20 |