728x90
반응형
SMALL
Stack의 특징
- 맨 마지막의 위치(top)에서만 자료를 추가, 삭제, 꺼내올 수 있습니다. (중간의 자료를 꺼낼 수 없습니다.)
- Last In First Out (후입 선출) 구조입니다.
- 택배 상자가 쌓여 있는 모양이라고 생각하면 이해하기 쉽습니다.
- 가장 최근의 자료를 찾아오거나 게임에서 히스토리를 유지하고 이를 무를 때 사용할 수 있습니다.
- 함수의 메모리는 호출 순서에 따른 stack구조입니다.
- jdk 클래스: Stack
배열을 활용하여 Stack 구현하기
MyArrayStack.java
import ch37.MyArray;
public class MyArrayStack {
MyArray arrayStack;
int top;
public MyArrayStack() {
top = 0;
arrayStack = new MyArray();
}
public MyArrayStack(int size) {
top = 0;
arrayStack = new MyArray(size);
}
public void push(int data) {
// 배열일 경우는 꽉 찼는지 확인을 해야한다.
if(isFull()) {
System.out.println("Stack is Full");
return;
}
arrayStack.addElement(data);
top++;
}
public int pop() {
if(isEmpty()) { // 데이터가 비어있을 경우
System.out.println("Stack is Empty");
return MyArray.ERROR_NUM;
}
return arrayStack.removeElement(--top);
}
public int peek() {
if(isEmpty()) { // 데이터가 비어있을 경우
System.out.println("Stack is Empty");
return MyArray.ERROR_NUM;
}
return arrayStack.getElement(--top);
}
public boolean isFull() {
if(top == arrayStack.ARRAY_SIZE) {
return true;
}
else return false;
}
public boolean isEmpty() {
if(top == 0) {
return true;
}
else return false;
}
public void printAll() {
arrayStack.printAll();
}
}
MyArrayStackTest.java
public class MyArrayStackTest {
public static void main(String[] args) {
MyArrayStack stack = new MyArrayStack(3);
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.printAll();
System.out.println("==========");
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println("==========");
System.out.println(stack.peek());
}
}
출력 결과
Stack is Full
10
20
30
==========
30
20
==========
10
728x90
반응형
LIST
'Java' 카테고리의 다른 글
[JAVA] 자바 - <T extends 클래스> 사용하기 (0) | 2022.01.10 |
---|---|
[JAVA] 자바 - 큐(Queue) 구현하기 (0) | 2022.01.05 |
[JAVA] 자바 - 연결리스트(LinkedList) 구현하기 (0) | 2022.01.04 |
[JAVA] 자바 - 배열 구현하기 (0) | 2022.01.04 |
[JAVA] 자바 - 자료구조 (0) | 2022.01.04 |