push(데이터) : 스택 위에 새로운 데이터를 추가pop() : 스택 맨 위 데이터를 꺼내고 제거peek() or top() : 스택 맨 위 데이터를 제거하지 않고 조회만 한다.isEmpty() : 스택이 비어있는지 확인스택은 보통 배열이나 연결 리스트(Linked List)를 이용해서 만들 수 있다.
push : O(1)pop : O(1)peek : O(1)isEmpty : O(1)💡 스택은 모든 기본 연산이 매우 빠르다(상수 시간, O(1))
#include <iostream>
using namespace std;
#define MAX 100 // 스택 최대 크기
class Stack {
int arr[MAX];
int top; // 스택의 가장 위를 가리키는 인덱스
public:
Stack() {
// 비어 있는 상태
top = -1;
}
bool isEmpty() {
return top == -1;
}
bool isFull() {
return top == MAX - 1;
}
void push(int value) {
if (isFull()) {
cout << "Stack Full\n";
return;
}
arr[++top] = value;
}
int pop() {
if (isEmpty()) {
cout << "Stack Empty\n";
return -1; // 에러값
}
return arr[top--];
}
int peek() {
if (isEmpty()) {
cout << "Stack Empty\n";
return -1;
}
return arr[top];
}
};
int main() {
Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << endl; // 30 출력
cout << s.peek() << endl; // 20 출력
cout << s.pop() << endl; // 20 출력
}
메모리 안에서 스택의 사용
메모리 전체 공간
┌────────────────────┐
│ 코드/데이터 영역 │
├────────────────────┤
│ 힙 영역 (아래→위) │ │ ↑↑↑ 확장
├────────────────────┤
│ 스택 영역 (위→아래) │ │ ↓↓↓ 확장
└────────────────────┘