반응형
Stack
- 스택이란 매모리 중의 하나입니다.
- 참조 : 2023.01.08 - [☕ 자바 JAVA/☕ 개발환경] - [JAVA]단순히 정리한 JVM구조와 Memory(+ static)
호출 스택
call stack


- 메서드 수행에 필요한 저장공간(memory place)
- 메서드가 호출call되면 호출스택에 메모리를 할당하고, 끝나면 해제.
- 이와 같이 후입선출 Last In First Out(LIFO)로 나중에 넣은 데이터를 먼저 꺼냅니다.
- project 시작
- main메서드 실행.
- println 호출 → main 대기.
- println 수행 종료/삭제됨 → call stack 삭제.
- main 다시 실행.
- main 에 있는 코드 모두 끝날 시 main메서드도 삭제 됨
- project 종료.
- 데이터를 넣는 작업을 Put
- 데이터를 꺼내는 작업을 Pop 이라 합니다.
배열로 스택을 만들어보면 이렇습니다.
더보기
package chap04;
public class IntStack {
private int max; // Stack size
private int ptr; // Stack pointer
private int[] stk; // Stack array
// Exception: Stack is empty
public class EmptyIntStackException extends RuntimeException {
public EmptyIntStackException() {
}
}
// Exception: Stack is full
public class OverflowIntStackException extends RuntimeException {
public OverflowIntStackException() {
}
}
// Base Constructor
public IntStack() {
}
// Constructor
public IntStack(int capacity) {
ptr = 0;
max = capacity;
try {
stk = new int[max]; // Create stack array
} catch (OutOfMemoryError e) { // Stack allocation failed
max = 0;
}
}
public int push(int x) throws OverflowIntStackException {
if (ptr >= max) { // Stack is full
throw new OverflowIntStackException();
}
return stk[ptr++] = x; // Push x
}
public int pop() throws EmptyIntStackException {
if (ptr <= 0) { // Stack is empty
throw new EmptyIntStackException();
}
return stk[--ptr];
}
public int peek() throws EmptyIntStackException {
if (ptr <= 0) { // Stack is empty
throw new EmptyIntStackException();
}
return stk[ptr - 1];
}
public int indexOf(int x) {
for (int i = ptr - 1; i >= 0; i--) { // Search from top
if (stk[i] == x) {
return i;
}
}
return -1; // x not found
}
public void clear() {
ptr = 0;
}
public int capacity() {
return max;
}
public int size() {
return ptr;
}
public boolean isEmpty() {
return ptr <= 0;
}
public boolean isFull() {
return ptr >= max;
}
public void dump() {
if (ptr <= 0) {
System.out.println("Stack is empty.");
} else {
for (int i = 0; i < ptr; i++) {
System.out.print(stk[i] + " ");
}
System.out.println();
}
}
}
참조 : https://www.youtube.com/watch?v=-mqL3LJ4iVc&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp&index=62
반응형
'☕ JAVA > ☕ 개념지식' 카테고리의 다른 글
[JAVA]@Annotation 종류와 사용법 (2) | 2024.11.29 |
---|---|
[JAVA]객체지향 4가지 원칙(특징) (0) | 2024.11.18 |
[JAVA]Object:모든 클래스의 조상 (0) | 2024.11.05 |
[JAVA]Error & Exception. 예외의 종류. (1) | 2024.11.03 |
☕ JAVA란 (0) | 2022.12.30 |