호출스택
'호출스택'은 메서드의 작업에 필요한 '메모리 공간'을 제공한다. 메서드가 호출되면, 호출 스택에 호출된 메서드를 위한 메모리가 할당되며, 이 메모리는 메서드가 작업을 수행하는 동안 지역변수(매개변수 포함)들과 연산의 중간 결과 등을 저장하는데 사용된다. 그리고 메서드가 작업을 마치면 할당되었던 메모리 공간은 반환되어 비워진다.
- 메서드가 호출되면 수행에 필요한 만큼의 메모리를 스택에 할당받는다.
- 메서드가 수행을 마치고 나면 사용했던 메모리를 반환하고 스택에서 제거된다.
- 호출스택의 제일 위에 있는 메서드가 현재 실행중인 메서드이다.
- 아래에 있는 메서드가 바로 위의 메서드를 호출한 메서드이다.
main메서드에도 더 이상 수행할 코드가 없으면 종료되어, 호출스택은 완전히 비워지게 되고 프로그램은 종료된다.
반환타입이 있는 메서드는 종료되면서 결과값을 자기가 호출한 메서드에게 반환한다. 대기상태에 있던 호출한 메서드는 넘겨받은 반환값으로 수행을 계속 진행하게 된다.
package Mission4;
import java.util.Scanner;
public class Stack {
private int index;
private int stackSize;
private char stackArr[];
//스택을 생성하는 생성자
public Stack(int stackSize) { //배열 stackSize를 입력받아 초기 배열을 생성
index = -1; //스택 포인터 초기화
this.stackSize = stackSize; //스택 사이즈 설정
stackArr = new char[this.stackSize]; //스택 배열 생성
}
//스택이 비어있는 상태인지 확인
public boolean isEmpty() {
//스택 포인터가 -1인 경우 데이터가 없는 상태이므로 true가 아닌경우 false를 return한다.
return (index == -1);
}
//스택이 가득찬 상태인지 확인
public boolean isFull() {
//스택 포인터가 스택의 마지막 인덱스와 동일한 경우 true가 아닌경우 false를 return한다.
return (index == this.stackSize - 1);
}
/**
* 1. 스택의 최상위에 새로운 자료를 삽입한다.
*/
public void push(char item) {
if (isFull()) {
System.out.println("Stack is full");
} else {
stackArr[++index] = item; //다음 스택 포인터가 가리키는 인덱스에 데이터 추가
//index에 char값을 채우고 index + 1 시킴
System.out.println("Inserted Item : " + item); //입력된 문자를 출력함
}
}
/**
* 2. 스택의 최상위(마지막) 데이터 추출 후 스택에서 제거한다.
*/
public char pop() {
if (isEmpty()) {
System.out.println("삭제 실패! Stack is empty"); //스택이 이미 비워져 있다면 출력
return 0;
} else {
System.out.println("Deleted Item : " + stackArr[index]);
return stackArr[index--];
}
}
/**
* 3. 스택의 최상위(마지막) 데이터 추출
*/
public char peek() {
if (isEmpty()) { //스택이 비워져 있는 상태일 때
System.out.println("Peeking fail! Stack is empty!");
return 0;
} else {
System.out.println("Peeked Item : " + stackArr[index]);
return stackArr[index];
}
}
/**
* 4. 스택에 존재하는 모든 자료들을 삭제한다.
*/
public void clear() {
if (isEmpty()) {
System.out.println("Stack is already empty!");
} else {
index = -1; //스택 포인터 초기화
stackArr = new char[this.stackSize]; //새로운 스택 배열 생성
System.out.println("Stack is clear!");
}
}
/**
* 5. 스택에 저장된 모든 데이터를 출력
*/
public void printStack() {
if (isEmpty()) { //이미 모든 스택이 비워져 있는 상태라면
System.out.println("Stack is empty!");
} else {
System.out.print("Stack elements : "); //스택이 비워져 있는 상태가 아니라면 출력
for (int i = 0; i <= index; i++) {
System.out.print(stackArr[i] + " ");
}
System.out.println();
}
}
}
class StackTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("스택 사이즈를 입력하시오.");
int stackSize = sc.nextInt();
Stack stack = new Stack(stackSize);
stack.push('A');
stack.printStack();
stack.push('B');
stack.printStack();
stack.push('C');
stack.printStack();
stack.pop();
stack.printStack();
stack.peek();
stack.printStack();
stack.clear();
stack.printStack();
}
}
'멋쟁이 사자처럼 2기 150일간의 기록' 카테고리의 다른 글
단순 삽입정렬이란? InsertionSort (1) | 2022.09.29 |
---|---|
단순 삽입정렬이란? (0) | 2022.09.28 |
단순 선택정렬(Selection Sort) 란? (0) | 2022.09.28 |
자바 5일차 과제 Employee 상속 (0) | 2022.09.26 |
멋쟁이 사자처럼 백엔드스쿨 2기 8일차 D - 143 - 자바 객체지향 2파트 복습 (1) | 2022.09.26 |