Chapter 06
스택
Stack
Part 1  스택의 기본 · Stack Basics
Part 2  스택의 일반 구현 · General Stack Implementation
Part 3  스택의 응용 · Stack Applications
01
Part 1
스택의 기본
Stack Basics
스택의 개념, 원리, 그리고 간단한 구현을 학습합니다.

생활 속 스택 구조

Stack Structures in Daily Life
한국어

우리 주변의 스택

일상생활에서 스택 구조를 쉽게 찾을 수 있습니다.

아이스크림 콘

맨 처음 얹은 스쿱이 가장 마지막에 먹게 됩니다.

종이컵 수거함

처음 넣은 컵이 가장 마지막에 나옵니다.

막힌 주차장 (일방통행)

가장 먼저 들어간 차가 가장 나중에 나옵니다.

컵 1 (먼저) 컵 2 컵 3 (나중) 넣는 순서 빼는 순서

핵심 포인트

이처럼 나중에 넣은 것이 먼저 나오는 LIFO 구조가 바로 프로그래밍의 "스택"입니다!

English

Stacks Around Us

Stack structures can be easily found in everyday life.

Ice Cream Cone

The first scoop placed is eaten last.

Paper Cup Collector

The first cup put in comes out last.

Dead-End Parking Lot (One-Way)

The first car to enter is the last to leave.

Cup 1 (first) Cup 2 Cup 3 (last) Insert order Remove order

Key Point

This Last In, First Out (LIFO) structure is exactly what a "stack" is in programming!

스택의 개념

Concept of Stack
한국어

스택이란?

스택은 한쪽 끝이 막혀 있는 자료구조입니다. 막힌 주차장이나 종이컵 수거함처럼, 데이터를 넣고 빼는 곳이 한쪽(위쪽)뿐입니다.

LIFO / FILO

  • LIFO (Last In, First Out): 마지막에 넣은 것이 먼저 나온다
  • FILO (First In, Last Out): 처음 넣은 것이 마지막에 나온다
막힌 바닥 데이터 A 데이터 B 데이터 C top push / pop
핵심 용어
용어의미
push스택에 데이터를 삽입
pop스택에서 데이터를 추출
top스택의 가장 위 데이터(위치)
English

What is a Stack?

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).

LIFO / FILO

  • LIFO (Last In, First Out): The last item inserted comes out first
  • FILO (First In, Last Out): The first item inserted comes out last
Blocked bottom Data A Data B Data C top push / pop
Key Terms
TermMeaning
pushInsert data into the stack
popExtract data from the stack
topThe topmost data (position) in the stack

스택 원리: push, pop, top

Stack Principles
한국어

push와 pop의 원리

배열 기반 스택에서 top은 가장 위의 데이터 위치를 가리키는 인덱스입니다. 초기값은 -1(비어 있음)입니다.

빈 스택 top = -1 push A push A A top = 0 push B push B A B top = 1 pop 동작 A top = 0 B 추출!
push 동작

top을 1 증가시키고, stack[top]에 데이터를 저장합니다.

pop 동작

stack[top]에서 데이터를 꺼내고, top을 1 감소시킵니다.

English

How push and pop Work

In an array-based stack, top is the index pointing to the topmost data position. Its initial value is -1 (empty).

Empty top = -1 push A push A A top = 0 push B push B A B top = 1 pop operation A top = 0 B extracted!
push Operation

Increment top by 1, then store data at stack[top].

pop Operation

Retrieve data from stack[top], then decrement top by 1.

push와 pop 동작 상세

Push & Pop Operations Detail
한국어

단계별 동작

push 동작 (삽입)

1top += 1 : top을 1 증가시킨다
2stack[top] = data : 해당 위치에 데이터를 저장한다

pop 동작 (추출)

1data = stack[top] : top 위치의 데이터를 꺼낸다
2stack[top] = None : 해당 위치를 비운다
3top -= 1 : top을 1 감소시킨다
push 과정 A top=0 top+=1 B A top=1 pop 과정 B A top=1 top-=1 A top=0 B 추출!

주의 사항

  • 빈 스택에서 pop (top == -1) : 에러 발생 (underflow)
  • 꽉 찬 스택에 push (top == SIZE-1) : 오버플로우 (overflow)
English

Step-by-Step Operations

push Operation (Insert)

1top += 1 : Increment top by 1
2stack[top] = data : Store data at that position

pop Operation (Extract)

1data = stack[top] : Retrieve data at the top position
2stack[top] = None : Clear that position
3top -= 1 : Decrement top by 1
push process A top=0 top+=1 B A top=1 pop process B A top=1 top-=1 A top=0 B extracted!

Caution

  • Pop from empty stack (top == -1) : Error (underflow)
  • Push to full stack (top == SIZE-1) : Overflow

간단 구현: 스택 생성과 push

Simple Implementation: Create & Push
한국어

Code06-01: 스택 생성 및 push

크기 5의 배열로 스택을 생성하고, 데이터를 push 합니다.

# 스택 생성 stack = [None, None, None, None, None] top = -1 # push: 커피 top += 1 stack[top] = "커피" # push: 녹차 top += 1 stack[top] = "녹차" # push: 꿀물 top += 1 stack[top] = "꿀물" print("----- 스택 상태 -----") for i in range(len(stack)-1, -1, -1): print(stack[i])

실행 결과

----- 스택 상태 ----- None None 꿀물 녹차 커피
push 후 스택 상태 [0] [1] [2] [3] [4] 커피 녹차 꿀물 None None top=2
English

Code06-01: Create Stack & Push

Create a stack with an array of size 5 and push data into it.

# Create stack stack = [None, None, None, None, None] top = -1 # push: coffee top += 1 stack[top] = "커피" # push: green tea top += 1 stack[top] = "녹차" # push: honey water top += 1 stack[top] = "꿀물" print("----- Stack Status -----") for i in range(len(stack)-1, -1, -1): print(stack[i])

Output

----- Stack Status ----- None None 꿀물 녹차 커피
Stack after pushes [0] [1] [2] [3] [4] 커피 녹차 꿀물 None None top=2

간단 구현: pop

Simple Implementation: Pop
한국어

Code06-02: pop 구현

스택에서 데이터를 하나씩 꺼내는(pop) 코드입니다.

# 이전 상태의 스택 stack = ["커피", "녹차", "꿀물", None, None] top = 2 # 첫 번째 pop data = stack[top] stack[top] = None top -= 1 print("pop -->", data) # 두 번째 pop data = stack[top] stack[top] = None top -= 1 print("pop -->", data) # 세 번째 pop data = stack[top] stack[top] = None top -= 1 print("pop -->", data)

실행 결과

pop --> 꿀물 pop --> 녹차 pop --> 커피
pop 전 None None 꿀물 녹차 커피 top=2 3회 pop 후 None None None None None top=-1 추출 순서 1. 꿀물 2. 녹차 3. 커피

LIFO 확인!

마지막에 넣은 "꿀물"이 가장 먼저 나오고, 처음 넣은 "커피"가 가장 마지막에 나옵니다.

English

Code06-02: Pop Implementation

Code that extracts (pops) data one by one from the stack.

# Stack from previous state stack = ["커피", "녹차", "꿀물", None, None] top = 2 # First pop data = stack[top] stack[top] = None top -= 1 print("pop -->", data) # Second pop data = stack[top] stack[top] = None top -= 1 print("pop -->", data) # Third pop data = stack[top] stack[top] = None top -= 1 print("pop -->", data)

Output

pop --> 꿀물 pop --> 녹차 pop --> 커피
Before pop None None 꿀물 녹차 커피 top=2 After 3 pops None None None None None top=-1 Extraction order 1. 꿀물 2. 녹차 3. 커피

LIFO Confirmed!

The last item pushed, "꿀물", comes out first, and the first item pushed, "커피", comes out last.

Part 1 실습

Part 1 Practice
한국어

직접 해보기

Self06-01: push 함수 작성

아래 코드를 완성하여 push 함수를 직접 작성하시오.

SIZE = 5 stack = [None] * SIZE top = -1 def push(data): global top # 여기에 코드를 작성하세요 # 1. 스택이 꽉 찼는지 확인 # 2. top을 1 증가 # 3. stack[top]에 data 저장 push("커피") push("녹차") push("꿀물") print("스택 상태:", stack)

기대 출력

스택 상태: ['커피', '녹차', '꿀물', None, None]
Self06-02: pop 함수 작성

아래 코드를 완성하여 pop 함수를 직접 작성하시오.

SIZE = 5 stack = ["커피", "녹차", "꿀물", None, None] top = 2 def pop(): global top # 여기에 코드를 작성하세요 # 1. 스택이 비어있는지 확인 # 2. stack[top]에서 data 꺼내기 # 3. stack[top]을 None으로 # 4. top을 1 감소 # 5. data 반환 print("pop -->", pop()) print("pop -->", pop()) print("pop -->", pop())

기대 출력

pop --> 꿀물 pop --> 녹차 pop --> 커피
English

Hands-On Practice

Self06-01: Write the push Function

Complete the code below to write the push function yourself.

SIZE = 5 stack = [None] * SIZE top = -1 def push(data): global top # Write your code here # 1. Check if stack is full # 2. Increment top by 1 # 3. Store data at stack[top] push("커피") push("녹차") push("꿀물") print("Stack status:", stack)

Expected Output

Stack status: ['커피', '녹차', '꿀물', None, None]
Self06-02: Write the pop Function

Complete the code below to write the pop function yourself.

SIZE = 5 stack = ["커피", "녹차", "꿀물", None, None] top = 2 def pop(): global top # Write your code here # 1. Check if stack is empty # 2. Retrieve data from stack[top] # 3. Set stack[top] to None # 4. Decrement top by 1 # 5. Return data print("pop -->", pop()) print("pop -->", pop()) print("pop -->", pop())

Expected Output

pop --> 꿀물 pop --> 녹차 pop --> 커피
02
Part 2
스택의 일반 구현
General Stack Implementation
isStackFull · push · isStackEmpty · pop · peek

스택 초기화 Stack Initialization

한국어
크기 지정 및 빈 스택 생성

SIZE 값으로 스택 크기를 결정하고, 리스트 내포를 사용하여 None으로 채운 배열을 만든다.

top = -1은 스택이 비어 있음을 의미한다.

SIZE = 5 # 빈 스택 생성 (리스트 내포) stack = [None for _ in range(SIZE)] top = -1
None [4] None [3] None [2] None [1] None [0] top (-1)
SIZE 값만 변경하면 원하는 크기의 스택을 생성할 수 있다.
English
Set Size and Create Empty Stack

SIZE determines the stack capacity. Use list comprehension to create an array filled with None.

top = -1 means the stack is empty.

SIZE = 5 # Create empty stack (list comprehension) stack = [None for _ in range(SIZE)] top = -1
None [4] None [3] None [2] None [1] None [0] top (-1)
Change SIZE to create a stack of any desired capacity.

isStackFull 함수 isStackFull Function

한국어
스택이 꽉 찼는지 확인

topSIZE-1과 같거나 크면 스택이 꽉 찬 상태이다.

SIZE = 5일 때, top == 4이면 꽉 찬 상태 (True 반환).

def isStackFull(): global SIZE, stack, top if (top >= SIZE-1): # top이 SIZE-1 이상이면 return True # 꽉 찬 상태 else: return False # 여유 있음
꽉 찬 스택 (Full Stack) 커피 [4] 녹차 [3] 콜라 [2] 사이다 [1] 환타 [0] top (4) top(4) >= SIZE-1(4) → True
English
Check If Stack Is Full

If top is greater than or equal to SIZE-1, the stack is full.

When SIZE = 5, top == 4 means full (returns True).

def isStackFull(): global SIZE, stack, top if (top >= SIZE-1): # if top >= SIZE-1 return True # stack is full else: return False # space available
Full Stack 커피 [4] 녹차 [3] 콜라 [2] 사이다 [1] 환타 [0] top (4) top(4) >= SIZE-1(4) → True

push 함수 push Function

한국어
데이터 삽입 (Push)
1 isStackFull()로 꽉 찼는지 확인
2 top += 1 — top을 한 칸 위로 이동
3 stack[top] = data — 데이터 저장
def push(data): global SIZE, stack, top if (isStackFull()): print("스택이 꽉 찼습니다.") return top += 1 stack[top] = data
Before None [2] 녹차 [1] 커피 [0] top→ push ("환타") After 환타 [2] 녹차 [1] 커피 [0] top→ 스택이 꽉 찬 경우 (Full Stack) push("게토레이") → "스택이 꽉 찼습니다."
English
Insert Data (Push)
1 Check if full with isStackFull()
2 top += 1 — move top up by one
3 stack[top] = data — store data
def push(data): global SIZE, stack, top if (isStackFull()): print("Stack is full.") return top += 1 stack[top] = data
Before None [2] 녹차 [1] 커피 [0] top→ push ("환타") After 환타 [2] 녹차 [1] 커피 [0] top→ When Stack is Full push("게토레이") → "Stack is full."

isStackEmpty 함수 isStackEmpty Function

한국어
스택이 비었는지 확인

top-1이면 스택이 비어 있는 상태이다.

데이터가 하나도 없으면 True를 반환한다.

def isStackEmpty(): global SIZE, stack, top if (top == -1): # top이 -1이면 return True # 비어 있는 상태 else: return False # 데이터 있음
빈 스택 (Empty Stack) None [2] None [1] None [0] top (-1) top(-1) == -1 → True
비어 있는 스택에서 pop을 시도하면 오류가 발생할 수 있으므로 반드시 확인한다.
English
Check If Stack Is Empty

If top equals -1, the stack is empty.

Returns True when there is no data at all.

def isStackEmpty(): global SIZE, stack, top if (top == -1): # if top is -1 return True # stack is empty else: return False # data exists
Empty Stack None [2] None [1] None [0] top (-1) top(-1) == -1 → True
Always check before pop. Attempting pop on an empty stack may cause errors.

pop 함수 pop Function

한국어
데이터 추출 (Pop)
1 isStackEmpty()로 비었는지 확인
2 data = stack[top] — top 데이터 임시 저장
3 stack[top] = None — 해당 위치 비움
4 top -= 1 — top을 한 칸 아래로 이동
def pop(): global SIZE, stack, top if (isStackEmpty()): print("스택이 비었습니다.") return None data = stack[top] # top 데이터 저장 stack[top] = None # 위치 비움 top -= 1 # top 감소 return data
Before 환타 [2] 녹차 [1] 커피 [0] top→ pop() After None [2] 녹차 [1] 커피 [0] top→ 반환: "환타" 빈 스택에서 pop 시도 pop() → "스택이 비었습니다." → None 반환
English
Extract Data (Pop)
1 Check if empty with isStackEmpty()
2 data = stack[top] — save top data temporarily
3 stack[top] = None — clear the position
4 top -= 1 — move top down by one
def pop(): global SIZE, stack, top if (isStackEmpty()): print("Stack is empty.") return None data = stack[top] # save top data stack[top] = None # clear position top -= 1 # decrease top return data
Before 환타 [2] 녹차 [1] 커피 [0] top→ pop() After None [2] 녹차 [1] 커피 [0] top→ return: "환타" Pop on Empty Stack pop() → "Stack is empty." → returns None

peek 함수 peek Function

한국어
데이터 확인 (Peek)

top 위치의 데이터를 확인만 하고 꺼내지 않는다.

스택의 상태가 변하지 않는 것이 pop과의 핵심 차이점이다.

def peek(): global SIZE, stack, top if (isStackEmpty()): print("스택이 비었습니다.") return None return stack[top] # 꺼내지 않고 반환만
peek() 실행 후에도 스택 변화 없음 환타 [2] 녹차 [1] 커피 [0] top (2) "환타" 반환값
peek()pop()
데이터 반환OO
데이터 제거XO
top 변화변화 없음top -= 1
스택 상태유지변경
English
View Data (Peek)

Check the data at top position without removing it.

The stack state remains unchanged -- this is the key difference from pop.

def peek(): global SIZE, stack, top if (isStackEmpty()): print("Stack is empty.") return None return stack[top] # return without removing
Stack unchanged after peek() 환타 [2] 녹차 [1] 커피 [0] top (2) "환타" return
peek()pop()
Returns dataOO
Removes dataXO
top changesNo changetop -= 1
Stack statePreservedModified

스택 완성: 대화형 프로그램 Complete Stack: Interactive Program

한국어
Code06-08 : 대화형 스택 프로그램

모든 함수를 조합하여 사용자와 대화하며 동작하는 완성된 스택 프로그램이다.

메뉴: I(삽입) / E(추출) / V(확인) / X(종료)

## 전역 변수 및 함수 선언부 ## SIZE = 5 stack = [None for _ in range(SIZE)] top = -1 # isStackFull(), isStackEmpty() # push(), pop(), peek() 함수 포함 ## 메인 코드 ## while True: select = input("삽입(I), 추출(E), 확인(V), 종료(X) : ") if select == 'I' or select == 'i': data = input("입력할 데이터 : ") push(data) print("스택 상태 : ", stack) elif select == 'E' or select == 'e': data = pop() print("추출된 데이터 : ", data) print("스택 상태 : ", stack) elif select == 'V' or select == 'v': data = peek() print("확인된 데이터 : ", data) print("스택 상태 : ", stack) elif select == 'X' or select == 'x': break else: print("잘못된 입력입니다.")
함수 관계도 메인 코드 push() pop() peek() isStackFull() isStackEmpty() I → push() → isStackFull() → 데이터 삽입 → 스택 출력
English
Code06-08 : Interactive Stack Program

A complete stack program that combines all functions and interacts with the user.

Menu: I(Insert) / E(Extract) / V(View) / X(Exit)

## Global variables & function declarations ## SIZE = 5 stack = [None for _ in range(SIZE)] top = -1 # isStackFull(), isStackEmpty() # push(), pop(), peek() included ## Main code ## while True: select = input("Insert(I), Extract(E), View(V), Exit(X) : ") if select == 'I' or select == 'i': data = input("Data to insert : ") push(data) print("Stack state : ", stack) elif select == 'E' or select == 'e': data = pop() print("Extracted data : ", data) print("Stack state : ", stack) elif select == 'V' or select == 'v': data = peek() print("Peeked data : ", data) print("Stack state : ", stack) elif select == 'X' or select == 'x': break else: print("Invalid input.")
Function Relationships Main Code push() pop() peek() isStackFull() isStackEmpty() I → push() → isStackFull() → insert data → print stack

Part 2 실습 Part 2 Practice

한국어
실습 1

스택 크기를 사용자에게 입력받아 대화형 스택 프로그램을 실행하시오.

Code06-08을 참고하되, SIZE를 input()으로 입력받도록 수정한다.
실행 예시:
스택 크기 입력 : 3
삽입(I), 추출(E), 확인(V), 종료(X) : I
입력할 데이터 : 커피
스택 상태 : ['커피', None, None]
삽입(I), 추출(E), 확인(V), 종료(X) : I
입력할 데이터 : 녹차
스택 상태 : ['커피', '녹차', None]
삽입(I), 추출(E), 확인(V), 종료(X) : V
확인된 데이터 : 녹차
스택 상태 : ['커피', '녹차', None]
실습 2

peek() 함수와 pop() 함수를 비교하여 설명하시오.

다음 항목을 중심으로 비교하시오:
  • 데이터 반환 여부
  • 데이터 제거 여부
  • top 값의 변화
  • 스택 상태의 변화
  • 사용 목적의 차이
English
Practice 1

Run the interactive stack program with a user-input stack size.

Refer to Code06-08, but modify SIZE to be received via input().
Sample run:
Enter stack size : 3
Insert(I), Extract(E), View(V), Exit(X) : I
Data to insert : 커피
Stack state : ['커피', None, None]
Insert(I), Extract(E), View(V), Exit(X) : I
Data to insert : 녹차
Stack state : ['커피', '녹차', None]
Insert(I), Extract(E), View(V), Exit(X) : V
Peeked data : 녹차
Stack state : ['커피', '녹차', None]
Practice 2

Compare and explain the peek() function vs the pop() function.

Compare based on the following criteria:
  • Whether data is returned
  • Whether data is removed
  • Change in top value
  • Change in stack state
  • Difference in use cases
03
Part 3
스택의 응용
Stack Applications
웹 서핑 뒤로가기 · 괄호 매칭 검사 · 헨젤과 그레텔 · 파일 역순 출력

웹 서핑 뒤로가기 Code06-09

Web Browser Back Navigation
한국어
개념

웹 브라우저의 뒤로가기 기능은 스택으로 구현할 수 있다.

방문할 때마다 URL을 push, 뒤로 갈 때 pop하여 이전 페이지로 이동한다.

[ Push – 방문 ] naver.com daum.net nate.com ← 먼저 push ← 마지막 push (top) [ Pop – 뒤로가기 ] nate.com ← 1번째 pop daum.net ← 2번째 pop naver.com ← 3번째 pop
# 방문할 URL 목록 urls = ['naver.com', 'daum.net', 'nate.com'] # 사이트 방문 (push) for url in urls: push(url) print('방문: ' + url) # 뒤로가기 (pop) print('===== 뒤로가기 =====') while not isStackEmpty(): url = pop() print('재방문: ' + url)
English
Concept

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.

[ Push – Visit ] naver.com daum.net nate.com ← first push ← last push (top) [ Pop – Go Back ] nate.com ← 1st pop daum.net ← 2nd pop naver.com ← 3rd pop
# List of URLs to visit urls = ['naver.com', 'daum.net', 'nate.com'] # Visit sites (push) for url in urls: push(url) print('Visit: ' + url) # Go back (pop) print('===== Go Back =====') while not isStackEmpty(): url = pop() print('Revisit: ' + url)

괄호 매칭 검사 개념

Bracket Matching Concept
한국어
올바른 괄호 vs 잘못된 괄호
수식결과이유
(A+B)✓ 올바름짝이 맞음
)A+B(✗ 오류순서가 틀림
((A+B)-C✗ 오류개수 불일치
(A+B]✗ 오류종류 불일치
(<A+{B-C}/[C*D]>)✓ 올바름여러 종류 매칭
알고리즘
1여는 괄호 → push
2닫는 괄호 → pop하여 비교
3짝이 안 맞으면 → False
4끝난 후 스택이 비면 → True
검사: ( < A + { B } > ) 읽기: ( < A + { B } > ) 스택: ( ( < ( < { ( < ( 비어있음 → True ✓
English
Correct vs Incorrect Brackets
ExpressionResultReason
(A+B)✓ CorrectMatching pair
)A+B(✗ ErrorWrong order
((A+B)-C✗ ErrorCount mismatch
(A+B]✗ ErrorType mismatch
(<A+{B-C}/[C*D]>)✓ CorrectMulti-type match
Algorithm
1Opening bracket → push
2Closing bracket → pop and compare
3If mismatch → False
4After all chars, if stack empty → True
Check: ( < A + { B } > ) Read: ( < A + { B } > ) Stack: ( ( < ( < { ( < ( Empty → True ✓

괄호 매칭 처리 과정

Bracket Matching Process
한국어
처리 순서
1수식에서 문자를 하나씩 읽는다
2여는 괄호 ( [ { < → 스택에 push
3닫는 괄호 ) ] } > → 스택에서 pop하여 비교
4짝이 안 맞으면 → 즉시 False 반환
5모든 문자 처리 후 스택이 비어있으면 → True, 아니면 → False
예시: (A+B] 검사 '(' 읽기 → push ( ← top 'A' 읽기 → 무시 ( '+' 읽기 → 무시 ( 'B' 읽기 → 무시 ( ']' 읽기 → pop pop → '(' ']' ≠ ')' → False! 종류 불일치
English
Processing Steps
1Read characters one by one from the expression
2Opening bracket ( [ { <push onto stack
3Closing bracket ) ] } >pop from stack and compare
4If mismatch → immediately return False
5After all chars: if stack empty → True, otherwise → False
Example: checking (A+B] '(' read → push ( ← top 'A' read → skip ( '+' read → skip ( 'B' read → skip ( ']' read → pop pop → '(' ']' ≠ ')' → False! Type mismatch

괄호 매칭 구현 Code06-10

Bracket Matching Implementation
한국어
def checkBracket(expr): for ch in expr: if ch in '([{<': push(ch) # 여는 괄호 push elif ch in ')]}>': out = pop() # 닫는 괄호 → pop if ch == ')' and out == '(': pass elif ch == ']' and out == '[': pass elif ch == '}' and out == '{': pass elif ch == '>' and out == '<': pass else: return False # 불일치 else: pass # 괄호 아닌 문자 무시 if isStackEmpty(): return True # 모두 매칭됨 else: return False # 여는 괄호 남음
테스트 결과
'(A+B)' ==> True ')A+B(' ==> False '((A+B)-C' ==> False '(A+B]' ==> False '(<A+{B-C}/[C*D]>)' ==> True
English
def checkBracket(expr): for ch in expr: if ch in '([{<': push(ch) # Push opening bracket elif ch in ')]}>': out = pop() # Closing bracket → pop if ch == ')' and out == '(': pass elif ch == ']' and out == '[': pass elif ch == '}' and out == '{': pass elif ch == '>' and out == '<': pass else: return False # Mismatch else: pass # Ignore non-bracket if isStackEmpty(): return True # All matched else: return False # Opening brackets remain
Test Results
'(A+B)' ==> True ')A+B(' ==> False '((A+B)-C' ==> False '(A+B]' ==> False '(<A+{B-C}/[C*D]>)' ==> True

응용예제: 헨젤과 그레텔 Ex06-01

Application: Hansel & Gretel
한국어
개념

헨젤이 과자의 집으로 가는 길에 색깔 돌을 떨어뜨린다 (push).

돌아올 때 돌을 주워가며 역순으로 집에 돌아온다 (pop).

과자집 push (돌 떨어뜨리기) pop (돌 주워가기) →
import random colors = ['빨강','파랑','초록','노랑','보라','주황'] random.shuffle(colors) # 과자의 집으로 가는 길 for color in colors: push(color) print('떨어뜨린 돌: ' + color) # 집으로 돌아오는 길 print('=== 돌아가는 길 ===') while not isStackEmpty(): stone = pop() print('주운 돌: ' + stone)
English
Concept

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).

Home R B G Y P O Candy push (drop stones) pop (pick up stones) →
import random colors = ['빨강','파랑','초록','노랑','보라','주황'] random.shuffle(colors) # On the way to the candy house for color in colors: push(color) print('Dropped stone: ' + color) # On the way back home print('=== Way Back Home ===') while not isStackEmpty(): stone = pop() print('Picked up stone: ' + stone)

응용예제: 파일 거꾸로 출력 Ex06-02

Application: Reverse File Output
한국어
개념: 이중 역순
1파일을 한 줄씩 읽어 스택에 push
2모든 줄을 pop하면 줄 순서가 역순
3각 줄의 문자를 미니 스택으로 역순 처리
파일 내용 Line 1: ABC Line 2: DEF Line 3: GHI push 줄 스택 ABC DEF GHI ← top pop 역순 줄 GHI DEF ABC 각 줄의 문자 역순: GHI → 문자 스택 → IHG DEF → 문자 스택 → FED ABC → 문자 스택 → CBA
# 파일 읽어서 줄 단위 push with open('data.txt', 'r') as f: for line in f: push(line.rstrip('\n')) # 줄 역순으로 pop, 각 줄 문자도 역순 while not isStackEmpty(): line = pop() # 미니 스택으로 문자 역순 charStack = [] for ch in line: charStack.append(ch) result = '' while charStack: result += charStack.pop() print(result)
English
Concept: Double Reversal
1Read file line by line, push each line
2Pop all lines to reverse line order
3Reverse characters in each line using a mini stack
File Content Line 1: ABC Line 2: DEF Line 3: GHI push Line Stack ABC DEF GHI ← top pop Reversed Lines GHI DEF ABC Reverse chars in each line: GHI → char stack → IHG DEF → char stack → FED ABC → char stack → CBA
# Read file and push each line with open('data.txt', 'r') as f: for line in f: push(line.rstrip('\n')) # Pop lines in reverse, reverse chars too while not isStackEmpty(): line = pop() # Mini stack to reverse characters charStack = [] for ch in line: charStack.append(ch) result = '' while charStack: result += charStack.pop() print(result)

Part 3 실습

Part 3 Practice
한국어
실습 1

괄호 매칭 프로그램에서 사용자 입력을 받아 검사하도록 수정하시오.

힌트: input() 함수를 사용하여 수식을 입력받고, checkBracket() 함수로 검사한다.
# 예시 출력 수식 입력: (A+{B*C}) 결과: True 수식 입력: (A+B] 결과: False
실습 2

주어진 문자열을 스택을 이용하여 뒤집는 프로그램을 작성하시오.

힌트: 문자를 하나씩 push한 후, 모두 pop하면 역순이 된다.
# 예시 출력 입력 문자열: Hello 뒤집은 결과: olleH 입력 문자열: Python 뒤집은 결과: nohtyP
English
Practice 1

Modify the bracket matching program to accept user input for validation.

Hint: Use the input() function to get an expression, then check with checkBracket().
# Sample output Enter expression: (A+{B*C}) Result: True Enter expression: (A+B] Result: False
Practice 2

Write a program to reverse a string using a stack.

Hint: Push each character, then pop all to get the reverse.
# Sample output Input string: Hello Reversed: olleH Input string: Python Reversed: nohtyP

전체 소스 코드 Code06-08

Complete Source Code
한국어 - 전체 코드
## 스택의 구현 ## SIZE = 5 stack = [None] * SIZE top = -1 def isStackFull(): global top, SIZE, stack if top >= SIZE - 1: return True else: return False def isStackEmpty(): global top, SIZE, stack if top == -1: return True else: return False def push(data): global top, SIZE, stack if isStackFull(): print('스택이 꽉 찼습니다!') return top += 1 stack[top] = data
English - Full Code
## Stack Implementation ## SIZE = 5 stack = [None] * SIZE top = -1 def isStackFull(): global top, SIZE, stack if top >= SIZE - 1: return True else: return False def isStackEmpty(): global top, SIZE, stack if top == -1: return True else: return False def push(data): global top, SIZE, stack if isStackFull(): print('Stack is full!') return top += 1 stack[top] = data

전체 소스 코드 Code06-08

Complete Source Code
한국어 - 전체 코드 (continued)
def pop(): global top, SIZE, stack if isStackEmpty(): print('스택이 비었습니다!') return None data = stack[top] stack[top] = None top -= 1 return data def peek(): global top, SIZE, stack if isStackEmpty(): print('스택이 비었습니다!') return None return stack[top]
English - Full Code (continued)
def pop(): global top, SIZE, stack if isStackEmpty(): print('Stack is empty!') return None data = stack[top] stack[top] = None top -= 1 return data def peek(): global top, SIZE, stack if isStackEmpty(): print('Stack is empty!') return None return stack[top]

전체 소스 코드 Code06-08

Complete Source Code
한국어 - 전체 코드 (continued)
## 전역 변수 및 메인 코드 ## SIZE = 5 stack = [None] * SIZE top = -1 print('스택 사용 예시 ---') push('커피') push('녹차') push('꿀물') push('콜라') push('주스') print('현재 스택: ', stack) push('사이다') # 스택이 꽉 참 print('peek --> ', peek()) while not isStackEmpty(): data = pop() print('pop --> ', data) print('현재 스택: ', stack) pop() # 스택이 비어있음
English - Full Code (continued)
## Global Variables and Main Code ## SIZE = 5 stack = [None] * SIZE top = -1 print('Stack usage example ---') push('커피') push('녹차') push('꿀물') push('콜라') push('주스') print('Current stack: ', stack) push('사이다') # Stack is full print('peek --> ', peek()) while not isStackEmpty(): data = pop() print('pop --> ', data) print('Current stack: ', stack) pop() # Stack is empty

전체 소스 코드 Code06-10

Complete Source Code
한국어 - 전체 코드
## 괄호 매칭 검사 ## def checkBracket(expr): for ch in expr: if ch in '([{<': push(ch) elif ch in ')]}>': out = pop() if ch == ')' and out == '(': pass elif ch == ']' and out == '[': pass elif ch == '}' and out == '{': pass elif ch == '>' and out == '<': pass else: return False else: pass if isStackEmpty(): return True else: return False # 테스트 exprs = ['(A+B)', ')A+B(', '((A+B)-C', '(A+B]', '(<A+{B-C}/[C*D]>)'] for e in exprs: # 매 검사 전 스택 초기화 top = -1 stack = [None] * SIZE result = checkBracket(e) print(e, '==>', result)
English - Full Code
## Bracket Matching Check ## def checkBracket(expr): for ch in expr: if ch in '([{<': push(ch) elif ch in ')]}>': out = pop() if ch == ')' and out == '(': pass elif ch == ']' and out == '[': pass elif ch == '}' and out == '{': pass elif ch == '>' and out == '<': pass else: return False else: pass if isStackEmpty(): return True else: return False # Test exprs = ['(A+B)', ')A+B(', '((A+B)-C', '(A+B]', '(<A+{B-C}/[C*D]>)'] for e in exprs: # Reset stack before each check top = -1 stack = [None] * SIZE result = checkBracket(e) print(e, '==>', result)
1 / 30