일상생활에서 스택 구조를 쉽게 찾을 수 있습니다.
맨 처음 얹은 스쿱이 가장 마지막에 먹게 됩니다.
처음 넣은 컵이 가장 마지막에 나옵니다.
가장 먼저 들어간 차가 가장 나중에 나옵니다.
이처럼 나중에 넣은 것이 먼저 나오는 LIFO 구조가 바로 프로그래밍의 "스택"입니다!
Stack structures can be easily found in everyday life.
The first scoop placed is eaten last.
The first cup put in comes out last.
The first car to enter is the last to leave.
This Last In, First Out (LIFO) structure is exactly what a "stack" is in programming!
스택은 한쪽 끝이 막혀 있는 자료구조입니다. 막힌 주차장이나 종이컵 수거함처럼, 데이터를 넣고 빼는 곳이 한쪽(위쪽)뿐입니다.
| 용어 | 의미 |
|---|---|
| push | 스택에 데이터를 삽입 |
| pop | 스택에서 데이터를 추출 |
| top | 스택의 가장 위 데이터(위치) |
A stack is a data structure where one end is blocked. Like a dead-end parking lot or a cup collector, data can only be inserted and removed from one end (the top).
| Term | Meaning |
|---|---|
| push | Insert data into the stack |
| pop | Extract data from the stack |
| top | The topmost data (position) in the stack |
배열 기반 스택에서 top은 가장 위의 데이터 위치를 가리키는 인덱스입니다. 초기값은 -1(비어 있음)입니다.
top을 1 증가시키고, stack[top]에 데이터를 저장합니다.
stack[top]에서 데이터를 꺼내고, top을 1 감소시킵니다.
In an array-based stack, top is the index pointing to the topmost data position. Its initial value is -1 (empty).
Increment top by 1, then store data at stack[top].
Retrieve data from stack[top], then decrement top by 1.
크기 5의 배열로 스택을 생성하고, 데이터를 push 합니다.
Create a stack with an array of size 5 and push data into it.
스택에서 데이터를 하나씩 꺼내는(pop) 코드입니다.
마지막에 넣은 "꿀물"이 가장 먼저 나오고, 처음 넣은 "커피"가 가장 마지막에 나옵니다.
Code that extracts (pops) data one by one from the stack.
The last item pushed, "꿀물", comes out first, and the first item pushed, "커피", comes out last.
아래 코드를 완성하여 push 함수를 직접 작성하시오.
아래 코드를 완성하여 pop 함수를 직접 작성하시오.
Complete the code below to write the push function yourself.
Complete the code below to write the pop function yourself.
SIZE 값으로 스택 크기를 결정하고, 리스트 내포를 사용하여 None으로 채운 배열을 만든다.
top = -1은 스택이 비어 있음을 의미한다.
SIZE determines the stack capacity. Use list comprehension to create an array filled with None.
top = -1 means the stack is empty.
top이 SIZE-1과 같거나 크면 스택이 꽉 찬 상태이다.
SIZE = 5일 때, top == 4이면 꽉 찬 상태 (True 반환).
If top is greater than or equal to SIZE-1, the stack is full.
When SIZE = 5, top == 4 means full (returns True).
isStackFull()로 꽉 찼는지 확인top += 1 — top을 한 칸 위로 이동stack[top] = data — 데이터 저장isStackFull()top += 1 — move top up by onestack[top] = data — store datatop이 -1이면 스택이 비어 있는 상태이다.
데이터가 하나도 없으면 True를 반환한다.
If top equals -1, the stack is empty.
Returns True when there is no data at all.
isStackEmpty()로 비었는지 확인data = stack[top] — top 데이터 임시 저장stack[top] = None — 해당 위치 비움top -= 1 — top을 한 칸 아래로 이동isStackEmpty()data = stack[top] — save top data temporarilystack[top] = None — clear the positiontop -= 1 — move top down by onetop 위치의 데이터를 확인만 하고 꺼내지 않는다.
스택의 상태가 변하지 않는 것이 pop과의 핵심 차이점이다.
| peek() | pop() | |
|---|---|---|
| 데이터 반환 | O | O |
| 데이터 제거 | X | O |
| top 변화 | 변화 없음 | top -= 1 |
| 스택 상태 | 유지 | 변경 |
Check the data at top position without removing it.
The stack state remains unchanged -- this is the key difference from pop.
| peek() | pop() | |
|---|---|---|
| Returns data | O | O |
| Removes data | X | O |
| top changes | No change | top -= 1 |
| Stack state | Preserved | Modified |
모든 함수를 조합하여 사용자와 대화하며 동작하는 완성된 스택 프로그램이다.
메뉴: I(삽입) / E(추출) / V(확인) / X(종료)
A complete stack program that combines all functions and interacts with the user.
Menu: I(Insert) / E(Extract) / V(View) / X(Exit)
스택 크기를 사용자에게 입력받아 대화형 스택 프로그램을 실행하시오.
input()으로 입력받도록 수정한다.peek() 함수와 pop() 함수를 비교하여 설명하시오.
Run the interactive stack program with a user-input stack size.
input().Compare and explain the peek() function vs the pop() function.
웹 브라우저의 뒤로가기 기능은 스택으로 구현할 수 있다.
방문할 때마다 URL을 push, 뒤로 갈 때 pop하여 이전 페이지로 이동한다.
The web browser's Back feature can be implemented with a stack.
Push each URL when visiting, pop to go back to the previous page.
| 수식 | 결과 | 이유 |
|---|---|---|
(A+B) | ✓ 올바름 | 짝이 맞음 |
)A+B( | ✗ 오류 | 순서가 틀림 |
((A+B)-C | ✗ 오류 | 개수 불일치 |
(A+B] | ✗ 오류 | 종류 불일치 |
(<A+{B-C}/[C*D]>) | ✓ 올바름 | 여러 종류 매칭 |
| Expression | Result | Reason |
|---|---|---|
(A+B) | ✓ Correct | Matching pair |
)A+B( | ✗ Error | Wrong order |
((A+B)-C | ✗ Error | Count mismatch |
(A+B] | ✗ Error | Type mismatch |
(<A+{B-C}/[C*D]>) | ✓ Correct | Multi-type match |
( [ { < → 스택에 push) ] } > → 스택에서 pop하여 비교( [ { < → push onto stack) ] } > → pop from stack and compare헨젤이 과자의 집으로 가는 길에 색깔 돌을 떨어뜨린다 (push).
돌아올 때 돌을 주워가며 역순으로 집에 돌아온다 (pop).
Hansel drops colored stones on the way to the candy house (push).
On the way back, he picks them up in reverse order to return home (pop).
괄호 매칭 프로그램에서 사용자 입력을 받아 검사하도록 수정하시오.
input() 함수를 사용하여 수식을 입력받고, checkBracket() 함수로 검사한다.주어진 문자열을 스택을 이용하여 뒤집는 프로그램을 작성하시오.
Modify the bracket matching program to accept user input for validation.
input() function to get an expression, then check with checkBracket().Write a program to reverse a string using a stack.